4

我正在使用 redux-persist 将数据存储在我的 react-native 应用程序中。这是代码:

store.js

import { createStore, compose, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import {
  persistStore,
 persistCombineReducers,
} from 'redux-persist';
import { AsyncStorage } from 'react-native';
import { composeWithDevTools } from 'redux-devtools-extension';
import user from './reducers/user';
import auth from './reducers/auth';

const config = {
  key: 'root',
  storage: AsyncStorage,
};

const reducers = persistCombineReducers(config, {
  user,
  auth
});

export const configureStore = () => {
 const store = createStore(
  reducers,
   compose(
    applyMiddleware(thunk),
    )
  );
  const persistor = persistStore(store);

  return { persistor, store };
};

然后在 App.js 我有这个:

const { persistor, store } = configureStore();
 const onBeforeLift = () => {
  // take some action before the gate lifts
  store.dispatch(startingApp());
}
return (
  <Provider store={store}>
    <PersistGate
      loading={<HomeLoader />}
      onBeforeLift={onBeforeLift}
      persistor={persistor}>
        <RootNav />
      </PersistGate>
  </Provider>

当我从 App.js componentDidMount 调度和操作时,一切正常。问题是,当我从组件触发操作时,例如,状态没有存储,所以当我重新启动应用程序时,状态就消失了。

我所做的只是调用动作并传递数据:

this.props.onSetAuthData(data.credentials);

正如我在控制台中看到的那样,状态已更新,但如果我重新启动应用程序,则只会保存由 App.js 中的操作创建的状态,而不是

也许这与 RootNav 组件有关?

也许我出口错误的减速机?我有 const user = (state = initialState, action = {}) => {} 导出默认用户。其他 reducer 也一样: const auth = (state = initialState, action = {}) => {} export default auth.

然后我用 combineReducers({auth, user}) 导出

这是错的吗?

4

2 回答 2

2

使用 Reacttotron 之类的工具来查看您的商店是否已持久化。

https://github.com/infinitered/reactotron

如果它已经持续存在,您的组件应该等到应用程序启动时商店补充水分。有时我不能使用 redux persistpersistgate来等待持久存储重新水化。所以我async componentWillMount在你的渲染中将商店和持久化器设置为状态,检查商店是否不为空(null)并且已经重新水化然后加载你的应用程序。

  constructor(){
    super();
    this.state = {store: null, persistor: null}
  }
  async componentWillMount () {
    const store = configureStore();
    this.setState({ store: store.store })
    this.setState({ persistor: store.persistor })
  }
  render(){
    return (
    if (this.state.store === null) {
      return (
        <View>
          <Text>Loading...</Text>
        </View>
        );
    }
    <Provider store={this.state.store} persistor={this.state.persistor}>
          <RootNav />
    </Provider>

还尝试将您的存储空间从 更改AsyncStoragestorage.

const config = {
  key: 'root',
  storage,
};

首先导入存储import storage from 'redux-persist/es/storage';

于 2017-12-20T02:41:15.937 回答
0

有时它会使用persistConfig中的键调用错误。尝试键:'主要'

const primary = {
key: 'root',
storage: AsyncStorage,
blacklist: [],
whitelist: ['user'],
};
于 2021-09-01T11:25:23.987 回答