Wix React-Native-Navigation v2 and redux-persist



我正在使用react-native-navigation和redux进行状态管理。我将每个组件注册为包装组件,将其连接到 redux 存储区。这工作得很好,与官方 react-native-navigation 文档中的 atoami 示例代码非常相似:https://wix.github.io/react-native-navigation/#/docs/showcases

import { Provider } from "react-redux";
import store from "./config/store";
...
function WrappedComponent(Component) {
  return function inject(props) {
    const EnhancedComponent = () => (
      <Provider store={store}>
        <Component {...props} />
      </Provider>
    );
    return <EnhancedComponent />;
  };
}
export function registerScreens() {
  Navigation.registerComponent("Initializing", () =>
    WrappedComponent(InitializingScreen)
  );
  Navigation.registerComponent("SignIn", () => WrappedComponent(SignInScreen));
...
}

存储对象为:

import { createStore, compose, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import reducers from "../reducers";
const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
export default createStore(
  reducers,
  composeEnhancer(applyMiddleware(thunk))
);

但是,我找不到为这些包装的组件设置 redux 持久的方法。我不想在 WrappedComponent 函数中执行此操作,因为随后会为每个单独的组件调用它。我也找不到这方面的明确文档。

我想我也可以使用AsyncStorage,但更愿意将其与Redux-persist一起使用。有人知道如何做到这一点吗?

这就是我处理 redux、redux 持久和 wix v2 反应原生导航

的方式

在你的store.js

import {createStore,applyMiddleware} from "redux";
import rootReducer from './reducers/RootReducer';
import thunk from 'redux-thunk';
import {persistStore, persistReducer} from 'redux-persist';
import {compact} from "lodash";
import storage from 'redux-persist/lib/storage';

const persistConfig = {
    key: 'app',
    storage,
};
const persistedReducer = persistReducer(persistConfig, rootReducer);
const middleware =compact([
    thunk.withExtraArgument()
]);

export const store = createStore( persistedReducer,applyMiddleware(...middleware));
export const persistor = persistStore(store);

然后在您的navigation.js或基本上注册屏幕的地方

import React from "react";
import {Navigation} from "react-native-navigation";
import {Provider} from 'react-redux';
import {PersistGate} from 'redux-persist/integration/react'
import {store, persistor} from "./config/store"; //Check this line
function WrappedComponent(Component) {
  return function inject(props) {
    const EnhancedComponent = () => (
     <Provider store={store}>
         <PersistGate loading={null} persistor={persistor}>
             <Component {...props}/>
         </PersistGate>
      </Provider>
    );
    return <EnhancedComponent />;
  };
}
// Then your normal registration
export function registerScreens() {
  Navigation.registerComponent("Initializing", () =>
    WrappedComponent(InitializingScreen)
  );
  Navigation.registerComponent("SignIn", () => WrappedComponent(SignInScreen));
...
}
import {persistStore} from 'redux-persist';
Navigation.events().registerAppLaunchedListener(() => {
 persistStore(store,null,()=>{
   setRoot();
});
});

你可以像这样用 react-native-navigation 添加 Redux-persist。

最新更新