【问题标题】:What are the pros and cons on using React Context API with the useReducer() hook?使用带有 useReducer() 钩子的 React Context API 有什么优点和缺点?
【发布时间】:2021-06-21 12:06:55
【问题描述】:

我正在开发一个 Web 应用程序,并且我正在使用 React Context 而不使用 useReducer() 挂钩。这是我如何在我的应用程序中使用上下文的一个简单示例:

const [stateValue, setStateValue] = useState("");
const [stateValue1, setStateValue1] = useState("");
const contextValue : MainContext = {
      stateValue: stateValue,
      setStateValue: setStateValue,
      stateValue1: stateValue1,
      setStateValue1: setStateValue1
}

因此,我将 contextValue 传递给我的上下文提供程序,并且每次子组件必须更改 stateValuex 时,只需调用 setStateValuex 即可触发所有子组件内 stateValuex 的重新渲染。 使用 Context 和 useReducer() 钩子有什么好处和坏处?

【问题讨论】:

    标签: javascript reactjs react-hooks react-context


    【解决方案1】:

    我将其作为两个问题来处理:1)useStateuseReducer 的优缺点 2)道具与上下文的优缺点。然后把这些答案放在一起。

    useReducer 如果你有一个复杂的状态,你想确保你的所有更新逻辑都在一个集中的位置,那么useReducer 会很有用。另一方面,useState 适用于不需要那种控制的简单状态。

    props 是将值从一个组件传递给其子组件的标准方法。如果您要通过它很短的距离,这是最简单和最好的方法。如果您需要将值沿组件树向下传递很长一段距离,则 context 很有用。如果你有很多情况下组件不是为自己接收 props,而是为了将其转发给子组件,那么这可能表明 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])
    

    【讨论】:

      【解决方案2】:

      当您使用钩子或自定义钩子时,它们的状态是独立的。 这意味着假设您在组件 A 和 B 中使用了 useReducer。状态与 A 中的 useReducer 完全不同,而如果您使用 contextAPI,状态是相同的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-13
        • 2021-12-21
        • 1970-01-01
        • 2010-09-06
        • 2010-09-06
        • 2018-04-03
        • 1970-01-01
        相关资源
        最近更新 更多