React:如何使用 react-router 在视图之间共享状态? [英] React: how can you share the state between views using react-router?

查看:49
本文介绍了React:如何使用 react-router 在视图之间共享状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

class App 扩展组件 {使成为() {返回 (<路由器><div className="应用程序"><Route exact={true} path="/" component={Home}/><Route path="/app/:user_id" component={Backend}/>

</路由器>);}}

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

解决方案

将状态提升到您的应用"组件中,然后通过它们的 props 传递每个组件需要的任何状态元素.

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

App.state = {homeRelatedStuff: {...},backendRelatedStuff: {...},共享的东西:{...}}

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

<Home homeStuff={this.state.homeRelatedStuff} sharedStuff={this.state.sharedStuff}/>}/>

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

你的 state 不必像我一样把它们分开,它可以更平坦,你可以将多个 props 传递给每个组件

I am using react-router to route to two views which are independent from each other. Currently I've been using a new state object in Home and Backend but I want to get rid of this because both include nested components.

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>
    );
  }
}

How is it possible to share the state between the views without using other frameworks like redux or flux?

解决方案

lift the state up into your 'App' component, then pass down whatever elements of the state each component needs through their props.

For example your state in App might look like:

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

Then when declaring which component to use, you pass down props:

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

*Note the slightly different method of listing the component as a function so you can pass props

Your state doesn't have to keep them separate like I have, it could be flatter and you pass down multiple props to each component

这篇关于React:如何使用 react-router 在视图之间共享状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆