通过道具反应全球状态

时间:2017-06-09 16:06:31

标签: reactjs typescript global-state

我使用共享全局状态如下:

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,最好的方法是什么?

由于

1 个答案:

答案 0 :(得分:1)

道具是只读的(参见文档here)。所以,你要么:

  1. 将globalstate实现为Dashboard组件中的状态,然后将处理程序传递给Dashboard的子级,以便他们可以更改globalState。例如:
  2. &#13;
    &#13;
    // 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;
    &#13;
    &#13;

    1. 使用状态管理库,例如reduxflux。使用这些库,您可以保持应用程序的整个状态,并使其可以在任何组件中访问。这可能是最好的选择,很多人都使用这些库来管理他们的应用程序的状态。

    2. 您可以将globalState存储在localStoragewindow全局变量中。可能不是一个好主意,但仍有可能。

相关问题