0

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

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

//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>
  )

}

4

1 回答 1

0

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

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

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

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

于 2021-07-22T01:09:54.450 回答