通过 props 反应全局状态
React global state via props
我使用共享的全局状态如下:
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
class 中,我需要更改 globalState
,最好的方法是什么?
谢谢
道具是只读的(参见文档 here)。所以,你要么:
- 在您的
Dashboard
组件中将 globalstate 实现为一个状态,然后将处理程序传递给 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>
}
}
我使用共享的全局状态如下:
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
class 中,我需要更改 globalState
,最好的方法是什么?
谢谢
道具是只读的(参见文档 here)。所以,你要么:
- 在您的
Dashboard
组件中将 globalstate 实现为一个状态,然后将处理程序传递给 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>
}
}