![](/img/trans.png)
[英]Reducer running twice when using useReducer and React Context API
[英]What are the pros and cons on using React Context API with the useReducer() hook?
我正在开发一个 web 应用程序,我正在使用 React Context 而不使用 useReducer() 钩子。 这是我如何在我的应用程序中使用 Context 的一个简单示例:
const [stateValue, setStateValue] = useState("");
const [stateValue1, setStateValue1] = useState("");
const contextValue : MainContext = {
stateValue: stateValue,
setStateValue: setStateValue,
stateValue1: stateValue1,
setStateValue1: setStateValue1
}
因此,我将 contextValue 传递给我的 Context Provider ,并且每次子组件必须更改 stateValuex 时,只需调用 setStateValuex 即可触发所有子组件内 stateValuex 的重新渲染。 使用 Context 和 useReducer() 钩子有什么好处和坏处?
我将其作为两个问题来处理:1) useState
与useReducer
的优缺点 2)道具与上下文的优缺点。 然后把这些答案放在一起。
如果您有一个复杂的 state 并希望确保所有更新逻辑都在一个集中位置,那么useReducer
会很有用。 另一方面, useState
于不需要那种控制的简单 state。
props 是将值从一个组件传递给其子组件的标准方法。 如果您要通过它很短的距离,这是最简单和最好的方法。 如果您需要将值沿组件树向下传递很长一段距离,则 context 很有用。 如果您有很多情况下组件不是为自己接收道具,而是为了将其转发给孩子,那么这可能表明上下文比道具更好。
const contextValue : MainContext = {
stateValue: stateValue,
setStateValue: setStateValue,
stateValue1: stateValue1,
setStateValue1: setStateValue1
}
PS:如果你的上下文值是 object,别忘了记住它。 如果不这样做,您将在每次渲染时创建一个全新的 object,这将迫使任何消耗上下文的组件也进行渲染
const contextValue: MainContext = useMemo(() => {
return {
stateValue: stateValue,
setStateValue: setStateValue,
stateValue1: stateValue1,
setStateValue1: setStateValue1
}
}, [stateValue, stateValue1])
当您使用钩子或自定义钩子时,它们的状态是独立的。 这意味着假设您在组件 A 和 B 中使用了 useReducer。A 中的 useReducer 中的 state 完全不同,而如果您使用 contextAPI,则 state 是相同的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.