简体   繁体   English

通过道具反应全局状态

[英]React global state via props

Im using a shared global state as the following: 我使用共享的全局状态,如下所示:

interface DashboardProps extends React.Props<Dashboard> {
    globalState? : GlobalState
}

export class Dashboard extends React.Component<DashboardProps, any>{

}

In AppLayout i call it: AppLayout我称之为:

<Route  path='/dashboard'>
   <Dashboard globalState={this.state} />
</Route>

let say that inside Dashboard class I need to change the globalState , whats the best way to do so? 假设在Dashboard类中,我需要更改globalState ,那么最好的方法是什么?

Thanks 谢谢

Props are readonly (see docs here ). 道具是只读的(请参见docs 此处 )。 So, you either: 因此,您要么:

  1. implement globalstate as a state in your Dashboard component, then pass down the handler to children of Dashboard so that they can change globalState . 在您的Dashboard组件中实现globalstate作为状态,然后将处理程序传递给Dashboard的子代,以便他们可以更改globalState For example: 例如:

 // dashboard component class Dashboard extends Component { constructor(props) { super(props); this.state = { globalState = /* some initial value */ } } // handler to change globalState. globalStateHandler = (data) => { // perhaps some processing... this.setState({ globalState: data, }) } render() { return <ChildComponentOne> <ChildComponentTwo> <SomeComponentOne globalStateHandler={this.globalStateHandler}/> <SomeComponentOne globalStateHandler={this.globalStateHandler}/> </ChildComponentTwo> </ChildComponentOne> } } 

  1. Use a state management library like redux , or flux . 使用状态管理库,例如reduxflux Using these libraries, you can keep the entire state of your apps and make them accessible in any of your components. 使用这些库,您可以保持应用程序的整体状态,并可以在任何组件中对其进行访问。 This is probably the best option and many people have use these libraries to manage the state of their apps. 这可能是最好的选择,许多人已经使用这些库来管理其应用程序的状态。

  2. You could store globalState in localStorage or window global variable. 您可以将globalState存储在localStoragewindow全局变量中。 Probably not a good idea, but possible nonetheless. 可能不是一个好主意,但是仍然可能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM