【问题标题】:React Hooks & useContext: Is This a Good Pattern?React Hooks & useContext:这是一个好的模式吗?
【发布时间】:2019-02-24 03:12:10
【问题描述】:

我正在使用 React Hooks 学习 useContext。我想将包含应用程序状态的单个对象传递给上下文消费者,例如:

<AppContextProvider.Provider value={AppState}>
  {props.children}
</AppContextProvider.Provider>

当然,我需要传递一些getterssetters 来启用子组件来更新应用程序状态。

这种模式是一种有效的方法吗?还有更好的模式吗?

const AppContext = React.createContext();

function AppContextProvider(props) {
    const AppState = {
        aVideoCallIsLive: [get, set] = useState(false),
        channelName: [get, set] = useState(null),
        localVideoStream: [get, set] = useState(null),
        selectedBottomNavIndex: [get, set] = useState(-1),
        loginDialogIsOpen: [get, set] = useState(false),
    }
}

【问题讨论】:

    标签: reactjs react-hooks react-state-management react-state


    【解决方案1】:

    为什么不使用 reducer 并传递单个调度函数?

    我相信它还建议您传递状态和调度是单独的上下文,否则调用调度将导致上下文中的所有内容重新呈现。

    https://reactjs.org/docs/hooks-faq.html#how-to-avoid-passing-callbacks-down

    https://reactjs.org/docs/hooks-reference.html#usereducer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-27
      • 2017-12-05
      • 2019-08-02
      • 1970-01-01
      • 2011-02-17
      • 1970-01-01
      • 1970-01-01
      • 2012-03-28
      相关资源
      最近更新 更多