我使用共享全局状态如下:
interface DashboardProps extends React.Props<Dashboard> {
globalState? : GlobalState
}
export class Dashboard extends React.Component<DashboardProps, any>{
}
在AppLayout
我称之为:
<Route path='/dashboard'>
<Dashboard globalState={this.state} />
</Route>
请说在Dashboard
课程内我需要更改globalState
,最好的方法是什么?
由于
答案 0 :(得分:1)
道具是只读的(参见文档here)。所以,你要么:
Dashboard
组件中的状态,然后将处理程序传递给Dashboard的子级,以便他们可以更改globalState
。例如:
// 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>
}
}
&#13;