首页 文章

React native和redux持续不起作用

提问于
浏览
1

我正在使用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})导出

这是错的吗?

1 回答

  • 1

    使用像Reacttotron这样的工具来查看您的商店是否持久存在 .

    https://github.com/infinitered/reactotron

    如果它使用 persistgate 来使用redux persist来等待持久存储被重新水合 . 所以我将商店和persistor设置为 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>
    

    还尝试将存储从 AsyncStorage 更改为 storage .

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

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

相关问题