当需要在不同组件之间共享反应状态时,最好的方法是什么?

问题描述 投票:0回答:1

我有一个情况,我有一个组件,我希望它是保持应用程序的状态的组件,它没有孩子,我希望其他路由中的其他组件连接到第一个组件状态。

我会举一个例子说明我的意思:

//this is the stateful component 
class A extends React.Component{ 
  state ={
    data:{}
  };

  render(){
   return (
    <div>
     {Object.keys(this.state.data).map(key=> <h1>{this.state.data[key]}</h1>)}
     <Link to="/routeB">Button</Link>
    </div>
   );
  }
}

class B extends React.Component{
//here i want to display data from component A state
}

class C extends React.Component{
//here i want to control the state of component A consider this component 
//to be a control panel for the user 
}

我知道,如果3个组件有任何关系,我可以通过道具,直到我得到我需要但我无法弄清楚这里有什么因为3个组件没有任何关系

请原谅我的英语,请考虑每个组成部分都在自己的路线上

javascript reactjs react-router-dom
1个回答
1
投票

对我来说,通量方法是最好的方法,最好的实现是Redux。你应该看看它

© www.soinside.com 2019 - 2024. All rights reserved.