【问题标题】:React global state via props通过 props 响应全局状态
【发布时间】:2017-06-09 16:06:30
【问题描述】:

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

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

谢谢

【问题讨论】:

  • 更好的方法是使用 redux。这个example 非常适合开始学习它。

标签: reactjs typescript global-state


【解决方案1】:

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

  1. 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>
  }

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-30
    • 2019-07-14
    • 2016-10-05
    • 2023-02-13
    • 2022-11-01
    • 2017-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多