使用 redux-persist 保存和检索状态 - React Native

2024-04-23

我是反应原生的新手,我第一次尝试保存我的应用程序的状态。

为了实现这一目标,我建议使用还原-持久化 https://github.com/rt2zz/redux-persist/blob/master/docs/recipes.md。 我希望在网络上找到更多有关它的示例和主题,但我觉得我对 redux-persist 如何工作的想法并不那么清晰。

我已按照 github 页面中的简短指南进行操作,但是一旦关闭并重新打开应用程序,我就看不到保存的状态值,但我看到了默认的初始状态值。

这是我的 app.js 文件:

import React, { Component } from 'react';
import { AsyncStorage } from 'react-native'
import { Provider } from 'react-redux';
import { createStore, applyMiddleware, compose } from 'redux';
import { persistStore, autoRehydrate } from 'redux-persist';
import ReduxThunk from 'redux-thunk';
import reducers from './reducers';
import Router from './Router';

class App extends Component {
  render() {
    const store = compose(applyMiddleware(ReduxThunk), autoRehydrate())(createStore)(reducers); 
    persistStore(store, {storage: AsyncStorage}, () => {
        console.log('restored');
    })
    return (
      <Provider store={store}>
        <Router />
      </Provider>
    );
  }
}

export default App;

我还需要别的东西吗?

我也想知道我怎样才能console.logredux-persistor 存储中的所有状态值。

提前致谢


你已经把persistStore into render方法。 持久化调用是一个副作用,永远不应该发生在render.

将其移至componentWillMount,正如 redux-persist 文档对你所说的那样

export default class AppProvider extends Component {

  constructor() {
    super()
    this.state = { rehydrated: false }
  }

  componentWillMount(){
    persistStore(store, {}, () => {
      this.setState({ rehydrated: true })
    })
  }

  render() {
    if(!this.state.rehydrated){
      return <div>Loading...</div>
    }
    return (
      <Provider store={store}>
         {() => <App />}
      </Provider>
    );
  }
}

您需要在渲染存储之前推迟初始化。这就是这段代码的作用

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 redux-persist 保存和检索状态 - React Native 的相关文章

随机推荐