【问题标题】:React Hooks - useState for global state managementReact Hooks - useState 用于全局状态管理
【发布时间】:2021-07-21 21:57:51
【问题描述】:

我知道现在有 Context API 应该用于全局应用状态管理。

但我想知道,使用 useState 管理应用程序的全局状态并像这样传递给 props 有什么问题(或不是最优的)吗?

//App.js

function App() {

  const [counterA, setCounterA] =  useState(0);
  const [counterB, setCounterB] =  useState(0);

  let masterStates = {
    counterA: counterA,
    counterB: counterB,
  }

  let masterFunctions = {
    setCounterA: setCounterA,
    setCounterB: setCounterB,
  }


  return (
    <div>
      ...
      <ChildComponent masterStates={masterStates} masterFunctions={masterFunctions} />
      ...
    </div>
  )
  
}

然后在我的 ChildComponent 中,我可以轻松地访问状态并像这样更新它:

//ChildComponent.js

function ChildComponent(props) {

  useEffect(() => {
    console.log("This will successfully log when counterA changes: ", props.masterStates.counterA);
  }, [props.masterStates.counterA]);

  return(
    <button onClick={() => props.masterFunctions.setCounterA(a => a + 1)}>
      {props.masterStates.counterA}
    </button>
  )

}

【问题讨论】:

  • 螺旋钻唯一的“错误”是它会变得复杂且迅速失控。我认为这个问题基于太多的意见。
  • 上下文 API 将用于传播相同的 useState 数据和 setter 函数,因此您的方法实际上没有任何问题,只要您有深度嵌套的组件,它就会变得有限(注意事项已知作为支柱钻孔)。
  • 还有一些渲染可能会意外影响数据或至少性能的问题......但是,归根结底......如果它只是两个组件(父/子(s))...当然...继续使用useState。添加另一个,这将是推动但可行的......不仅仅是使用context API

标签: reactjs react-redux react-hooks global-state


【解决方案1】:

感谢所有有见地的 cmets!这真的帮助我理清了问题。

我不熟悉“道具钻孔”这个术语,但现在它很有意义。

我将在这里留下一些有用的链接,供任何想了解更多信息的人使用:

https://kentcdodds.com/blog/prop-drilling

https://www.geeksforgeeks.org/what-is-prop-drilling-and-how-to-avoid-it/

https://medium.com/analytics-vidhya/props-drilling-in-react-js-934120a4906b


编辑:我刚刚在这里找到了这篇文章,他在其中描述了一种类似我的方法并列出了它的一些好处。

https://dev.to/bytebodger/rethinking-prop-drilling-state-management-in-react-1h61

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 2019-10-15
    • 2019-08-04
    • 2020-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多