Redux-Persist Library - 将数据从计数器保存到localStorage

时间:2018-03-16 15:25:15

标签: redux persist

美好的一天,

学习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;

1 个答案:

答案 0 :(得分:1)

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

  1. state.counter的值写入mapStateToProps
  2. 中的localStorage
  3. 执行createStore时,可以使用preloadedState传递第二个参数。因此,在您执行此操作之前,请从localStorage中读取以获取计数器的已保存值。
  4. 一些评论:

      reducer中的
    • state通常是具有属性的对象。它可以使用一个简单的数字,但如果你想学习redux,你会想在这里使用一个对象。
    • 一旦您对redux的基础知识感到满意,我建议继续使用更复杂的库,例如redux-persist。为了让一个简单的计数器工作,这一点太抽象了。