【发布时间】: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