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

Redux-Persist Library - Save data from counter to localStorage

美好的一天,

刚开始学习 redux 可能会比较混乱

这段代码中的步骤:

在这种情况下,需要将状态和数据保存到 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;

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

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

一些备注:

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