【问题标题】:Redux-Persist Library - Save data from counter to localStorageRedux-Persist 库 - 将数据从计数器保存到 localStorage
【发布时间】: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;

【问题讨论】:

    标签: redux persist


    【解决方案1】:

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

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

    一些备注:

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

    【讨论】:

      猜你喜欢
      • 2021-09-27
      • 2011-07-19
      • 2019-01-02
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      • 2013-12-24
      • 2015-10-14
      相关资源
      最近更新 更多