React-hooks:useReducer初始化函数 和 初始值 区别

文章介绍了如何在React中使用`useReducer`时,通过传递第三个参数来避免因组件频繁重新渲染导致的初始化函数频繁调用,从而提高性能。重点在于控制init函数的执行时机,仅在组件初次渲染时执行。
摘要由CSDN通过智能技术生成

useReducer 用法:

const [state, dispatch] = useReducer(reducer, initialArg, init?);

其中,initialArg 为初始值(必传),init 为初始函数(可选)。

  1. 当没有 init 参数时,state的初始值为 initialArg;
  2. 当有 init 参数时,state的初始值为 init(initialArg) 返回的值

当然,initialArg 也可以是调用函数 得到的返回值,如

const [state, dispatch] = useReducer(reducer, initState(1));

这种情况下,如果组件频繁重新渲染(比如当前组件是一个输入框,输入内容变更,组件也会跟着更新),那么每次渲染都会调用 initState
函数,导致性能变差。

想要避免上边的性能问题,可以借用 useReducer 的第三个参数:

const [state, dispatch] = useReducer(reducer, 1, initState);

和上边相比,这里是给useReducer 传了3个参数:

  • reducer:reducer函数,没变化;
  • 1: 初始值;
  • initState: 初始化函数;

此时,state = initState(1);

这个示例使用了一个初始化函数 initState,所以 initState 函数只会在初次渲染的时候进行调用。即使往输入框中输入内容导致组件重新渲染,初始化函数也不会被再次调用。

代码及演示如下:

1. 调用函数获取初始值:
const [state, dispatch] = useReducer(reducer, initState(0) );

完整代码:

import { useReducer, useState } from "react"


function reducer(state, action) {
    switch(action.type) {
        case 'increase':
            return state + 1;
        case 'decrease':
            return state - 1;
        default:
            throw new Error()
    }
}

export default function App() {
    const [state, dispatch] = useReducer(reducer, initState(0) );

    return (
        <>
            <button onClick={() => dispatch({type: 'increase'})}>+</button>
            <span>{state}</span>
            <button onClick={() => dispatch({type: 'decrease'})}>-</button>
        </>
    )   
}

function initState(state) {
    console.log('initState');
    return state + 100;
}

效果:
在这里插入图片描述

2. 使用初始化函数

重点代码:

const [state, dispatch] = useReducer(reducer, 0, initState );

完整代码:

import { useReducer, useState } from "react"


function reducer(state, action) {
    switch(action.type) {
        case 'increase':
            return state + 1;
        case 'decrease':
            return state - 1;
        default:
            throw new Error()
    }
}

export default function App() {
    const [state, dispatch] = useReducer(reducer, 0, initState );

    return (
        <>
            <button onClick={() => dispatch({type: 'increase'})}>+</button>
            <span>{state}</span>
            <button onClick={() => dispatch({type: 'decrease'})}>-</button>
        </>
    )   
}

function initState(state) {
    console.log('initState');
    return state + 100;
}

效果:
在这里插入图片描述

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端卡卡西呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值