美好的一天,
学习redux的开始可能令人困惑
此代码中的步骤:
onClick
操作,则先前提到的函数增量调度reducer 在这种情况下,需要将带有数据的状态保存到LocalStorage。
如何将 counter_state 保存到本地存储?
// 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;
答案 0 :(得分:1)
localStorage有一个非常简单的界面。我建议在mdn上查找它的API。由于您没有使用任何导入的持久性库,因此可以直接尝试将其用于学习目的:
state.counter
的值写入mapStateToProps
createStore
时,可以使用preloadedState传递第二个参数。因此,在您执行此操作之前,请从localStorage中读取以获取计数器的已保存值。一些评论:
state
通常是具有属性的对象。它可以使用一个简单的数字,但如果你想学习redux,你会想在这里使用一个对象。redux-persist
。为了让一个简单的计数器工作,这一点太抽象了。