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

时间:2018-03-05 23:01:04

标签: javascript reactjs react-router-dom

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

我将举例说明我的意思:

//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个组件没有任何关系

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

1 个答案:

答案 0 :(得分:1)

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