【问题标题】:React: how can you share the state between views using react-router?React:如何使用 react-router 在视图之间共享状态?
【发布时间】:2017-11-11 02:00:41
【问题描述】:

我正在使用 react-router 路由到两个彼此独立的视图。目前我一直在HomeBackend 中使用一个新的状态对象,但我想摆脱它,因为它们都包含嵌套组件。

class App extends Component {
  render() {
    return (
        <Router>
          <div className="App">
            <Route exact={true} path="/" component={Home} />

            <Route path="/app/:user_id" component={Backend} />
          </div>
        </Router>
    );
  }
}

如何在不使用 redux 或 Flux 等其他框架的情况下在视图之间共享状态?

【问题讨论】:

    标签: reactjs react-router react-router-dom


    【解决方案1】:

    将状态提升到您的“应用”组件中,然后通过它们的道具传递每个组件所需的任何状态元素。

    例如,您在 App 中的状态可能如下所示:

    App.state = {
      homeRelatedStuff: {...},
      backendRelatedStuff: {...},
      sharedStuff: {...}
    }
    

    然后在声明使用哪个组件的时候,你传递props:

    <Route path={"/"} component={() => <Home homeStuff={this.state.homeRelatedStuff} sharedStuff={this.state.sharedStuff}/>}/>
    

    *注意将组件列为函数的方法略有不同,以便您可以传递道具

    您的状态不必像我一样将它们分开,它可以更扁平,并且您将多个道具传递给每个组件

    【讨论】:

      猜你喜欢
      • 2022-01-14
      • 1970-01-01
      • 2017-04-27
      • 1970-01-01
      • 2019-01-31
      • 1970-01-01
      • 1970-01-01
      • 2019-05-16
      • 2020-06-23
      相关资源
      最近更新 更多