使用 React Context API 和 useReducer() 钩子有什么优缺点?
What are the pros and cons on using React Context API with the useReducer() hook?
我正在开发一个 Web 应用程序,我正在使用 React 上下文而不使用 useReducer() 挂钩。这是我如何在我的应用程序中使用上下文的简单示例:
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() 挂钩一起使用的优缺点是什么?
当您使用钩子或自定义钩子时,它们的状态是独立的。
这意味着假设您在组件 A 和 B 中使用了 useReducer。A、B 中 useReducer 的状态完全不同,而如果您使用 contextAPI,则状态相同。
我将其视为两个问题:1) pros/cons of useState
vs useReducer
2) pros/cons of props vs context。然后将这些答案放在一起。
useReducer
如果你有一个复杂的状态,你想确保所有的更新逻辑都在一个集中的位置,那么
useReducer
会很有用。另一方面,useState
适用于不需要那种控制的简单状态。
props 是将值从一个组件传递给其子组件的标准方式。如果您短距离通过它,这是最简单和最好的方法。如果您需要在组件树中很长一段时间内传递值,上下文很有用。如果在很多情况下,组件不是为自己接收 prop,而是为了将其转发给子组件,那么这可能表明 context 比 props 更好。
const contextValue : MainContext = {
stateValue: stateValue,
setStateValue: setStateValue,
stateValue1: stateValue1,
setStateValue1: setStateValue1
}
P.S:如果你的上下文值是一个对象,don't forget to memoize it。如果不这样做,每次渲染时都会创建一个全新的对象,这将强制任何使用上下文的组件也进行渲染
const contextValue: MainContext = useMemo(() => {
return {
stateValue: stateValue,
setStateValue: setStateValue,
stateValue1: stateValue1,
setStateValue1: setStateValue1
}
}, [stateValue, stateValue1])
我正在开发一个 Web 应用程序,我正在使用 React 上下文而不使用 useReducer() 挂钩。这是我如何在我的应用程序中使用上下文的简单示例:
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() 挂钩一起使用的优缺点是什么?
当您使用钩子或自定义钩子时,它们的状态是独立的。 这意味着假设您在组件 A 和 B 中使用了 useReducer。A、B 中 useReducer 的状态完全不同,而如果您使用 contextAPI,则状态相同。
我将其视为两个问题:1) pros/cons of useState
vs useReducer
2) pros/cons of props vs context。然后将这些答案放在一起。
useReducer
如果你有一个复杂的状态,你想确保所有的更新逻辑都在一个集中的位置,那么
useReducer
会很有用。另一方面,useState
适用于不需要那种控制的简单状态。
props 是将值从一个组件传递给其子组件的标准方式。如果您短距离通过它,这是最简单和最好的方法。如果您需要在组件树中很长一段时间内传递值,上下文很有用。如果在很多情况下,组件不是为自己接收 prop,而是为了将其转发给子组件,那么这可能表明 context 比 props 更好。
const contextValue : MainContext = {
stateValue: stateValue,
setStateValue: setStateValue,
stateValue1: stateValue1,
setStateValue1: setStateValue1
}
P.S:如果你的上下文值是一个对象,don't forget to memoize it。如果不这样做,每次渲染时都会创建一个全新的对象,这将强制任何使用上下文的组件也进行渲染
const contextValue: MainContext = useMemo(() => {
return {
stateValue: stateValue,
setStateValue: setStateValue,
stateValue1: stateValue1,
setStateValue1: setStateValue1
}
}, [stateValue, stateValue1])