Redux持久库-将数据从计数器保存到本地存储

Redux持久库-将数据从计数器保存到本地存储,redux,persist,Redux,Persist,你好 学习redux的开始可能会令人困惑 此代码中的步骤包括: 为增量创建减速器 创建存储 如果用户采取onClick操作,则函数增量调度前面提到的减速机 在同一组件中显示数据 使用存储在提供程序内部呈现组件 在这种情况下,需要将状态和数据保存到LocalStorage 如何将计数器状态保存到本地存储 // reducer function counter(state=0, action) { console.log('counter', action) switch(action.

你好

学习redux的开始可能会令人困惑

此代码中的步骤包括:

  • 为增量创建减速器
  • 创建存储
  • 如果用户采取
    onClick
    操作,则函数增量调度前面提到的减速机
  • 在同一组件中显示数据
  • 使用存储在提供程序内部呈现组件
在这种情况下,需要将状态和数据保存到LocalStorage

如何将计数器状态保存到本地存储

// 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,动作){
console.log('计数器',操作)
开关(动作类型){
案例“增量”:
返回状态+1;
返回状态;
}
}
///创建存储
常量存储=创建存储(计数器);
//反应组分
类计数器扩展了React.Component{
增量(){
这是我的道具({
类型:“增量”
});
}
render(){
返回(
{this.props.state}
+
)
}
}
const mapStateToProps=函数(状态){
返回{state};
}
常量计数器应用程序=连接(mapStateToProps)(计数器);
类Test5扩展了React.Component{
render(){
返回(
)
}
}
导出默认Test5;

localStorage有一个非常简单的界面。我建议在mdn上查找它的API。由于您没有使用任何要导入的持久性库,因此出于学习目的,不妨直接尝试:

  • state.counter的值写入
    MapStateTrops
  • 当您执行
    createStore
    操作时,您可以使用PRELOEDSTATE传递第二个参数。因此,在执行此操作之前,请从localStorage读取以获取计数器的保存值
  • 一些评论:

    • 减速器中的状态通常是具有属性的对象。它可能使用一个简单的数字,但如果您想学习redux,您将需要在这里使用一个对象
    • 一旦您熟悉了redux的基础知识,我建议您继续使用更复杂的库,如
      redux persist
      。要让一个简单的计数器工作起来,一下子就太抽象了