【问题标题】:Passing state props to components in route将状态道具传递给路由中的组件
【发布时间】:2018-07-28 15:53:10
【问题描述】:

我有以下反应结构

<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 组件将状态作为组件的更新属性传递?

【问题讨论】:

  • 跨页是什么意思?当您转到 GamePlay 组件时,您是否正在重新加载页面?您是否正确初始化了 redux 存储状态?
  • @krionz 是的,我正在重新加载页面,是的,我正在初始化 redux 存储状态。我需要初始化每个组件的状态还是 处理它?
  • 其实你所要做的就是停止重新加载页面。

标签: javascript reactjs redux react-redux


【解决方案1】:

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

【讨论】:

  • 是否有一些路由器选项可以不重新加载页面?我正在使用默认值,我认为会发生的是内容会被替换而无需重新加载。
  • @Kendall 这很可能与您导航到GamePlay 组件的方式有关。我的猜测是您使用的是href。尝试改用Link,它是react-router-dom 的一部分。见reacttraining.com/react-router/web/api/Link
猜你喜欢
  • 2016-10-28
  • 2020-10-08
  • 2020-11-06
  • 2021-01-03
  • 2017-05-29
  • 1970-01-01
  • 1970-01-01
  • 2020-08-16
  • 1970-01-01
相关资源
最近更新 更多