javascript - 将状态道具传递给路由中的组件
问题描述
我有以下反应结构
<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 组件将状态作为组件的更新属性传递?
解决方案
您可能正在重新加载页面。Redux 的状态存储在内存中,因此当您刷新页面时,它会丢失;看到这个。您可以使用redux-persist之类的东西将应用程序的状态存储在本地存储等中。
推荐阅读
- java - 如何使用单循环在两个数组中找到相同的元素?
- opencv - OpenCv获取到圆心的边缘距离
- sql - 如何编写查询以在 SQL 中排除一个部门中至少有一个 30 岁的人的所有员工
- python - 我想在 for 循环中串联运行多个变量,我想取 x 和 y 的每次迭代的总和
- cuda - %envregN 特殊寄存器保存什么?
- c# - 从 StringBuilder 中删除双新行
- c# - 抑制子进程的输出
- java - 如何使用输入和单元测试来测试java程序
- laravel - 在 Laravel API 中检索和保存通过 guzzle 多部分参数传递的图像
- c# - 使用 C# 按属性名称搜索 XML 值