首页 > 解决方案 > 将状态道具传递给路由中的组件

问题描述

我有以下反应结构

<Provider store={ store }>
              <Router>
                <Switch>
                  <Route path="/how-to" component={ Help } />
                  <Route path="/start" component={ StartPage } />
                  <Route path="/game" component={ GamePlay } />
                  <Route exact path="/" component={ Home } />
                </Switch>
              </Router>
        </Provider>

组件中有一个子StartPage组件与 store 状态下的属性交互

    .....
// pickBottle is an action from the store for the state
    <div className="text-center">
                        <button alt={bottleData.name} onClick={ (e) => { self.props.pickBottle(bottleData) } }>{bottleData.name}</button>
                      </div>
    ...

    export default connect(state => ({ bottle: state }), { pickBottle } )(PickerSlides)

该组件按预期工作,因为 this.props.bottle 在 click 事件上设置。然而,

当我导航到GamePlay具有

……

  render() {
    const { store } = this.context;
    console.log(store);

    return (

      <div id="game" className="panel" >
          <section className="row flexbox">
            <header>
              <hgroup>
                <h2 id="tries" className="tries">Tries: <span>{ this.state.tries }</span></h2>
                <h3 className="bottles">Opened:<span id="score" className="opened">{ this.state.bottlesOpened }</span></h3>
              </hgroup>
            </header>
            <article className="row flexbox">

            </article>
            </section>
      </div>
    );
  }
}
// map state to props

const mapStateToProps = ( state ) => {
  console.log('map state ', state );
    return {
        bottle: state,
    }
}

export default connect(mapStateToProps)(GamePlay)

console.log('map state', state )未定义

redux 是否可以跨页面使用组件?我是否需要使用 localStorage 来帮助 redux 通过路由持久化?

如何通过 Route/Switch 组件将状态作为组件的更新属性传递?

标签: javascriptreactjsreduxreact-redux

解决方案


您可能正在重新加载页面。Redux 的状态存储在内存中,因此当您刷新页面时,它会丢失;看到这个您可以使用redux-persist之类的东西将应用程序的状态存储在本地存储等中。


推荐阅读