【发布时间】:2018-08-25 17:30:56
【问题描述】:
早安,
开始学习 redux 可能会让人困惑
这段代码中的步骤:
- 为增量创建reducer
- 创建商店
- 如果用户采取
onClick动作,函数增量调度之前提到的reducer - 在同一个组件中显示数据
- 在 Provider 中使用 store 渲染组件
在这种情况下,需要将状态与数据一起保存到 LocalStorage。
如何将counter_state保存到local-storage?
// reducer
function counter(state=0, action) {
console.log('counter', action)
switch(action.type) {
case 'INCREMENT':
return state + 1;
return state;
}
}
///create store
const store = createStore(counter);
// React Component
class Counter extends React.Component {
increment() {
this.props.dispatch({
type: 'INCREMENT'
});
}
render() {
return (
<div>
{this.props.state}
<div>
<button onClick={this.increment.bind(this)}>+</button>
</div>
</div>
)
}
}
const mapStateToProps = function (state) {
return {state};
}
const CounterApp = connect(mapStateToProps)(Counter);
class Test5 extends React.Component {
render() {
return (
<Provider store={store}>
<CounterApp />
</Provider>
)
}
}
export default Test5;
【问题讨论】: