【问题标题】:Retrieving token from persisted store on app initialization React Native, Redux-Persist在应用程序初始化时从持久存储中检索令牌 React Native,Redux-Persist
【发布时间】:2019-01-03 08:40:01
【问题描述】:

我已经在我的应用程序中插入了 redux-persist。当应用程序被杀死后重新启动时,我想做的第一件事就是在重新水化的商店中获取我的身份验证令牌并检查令牌是否仍然有效。

我正在努力寻找这样做的好策略。作为第一个直觉,我会尝试在 componentDidMount 方法的根 App 组件中执行此操作。这是我的组件:

export default class App extends React.Component {
  componentDidMount(){
    console.log('in app componentDidmount')
    console.log(store.getState())
    console.log(persistor.getState())
  }

  render() {
    return (
      <Provider store={store}>
        <PersistGate persistor={persistor}>
          <Router />
        </PersistGate>
      </Provider>
    );
  }
}

但是store.getState() 给了我非再水合状态,persistor.getState() 给了我一个不可用的对象:

{ bootstrapped: false, registry: ["root"] }

这也是我的store.js 文件:

const persistConfig = {
  key: 'root',
  storage: AsyncStorage,
  stateReconciler: autoMergeLevel2, // see "Merge Process" section for details.
  blacklist: ['error', 'loading', 'backgroundImage'],
};
const pReducer = persistReducer(persistConfig, reducers);

export const store = createStore(pReducer, {}, compose(applyMiddleware(ReduxThunk)));

export const persistor = persistStore(store);

我怎样才能做到这一点?

【问题讨论】:

    标签: reactjs authentication react-native redux redux-persist


    【解决方案1】:

    方法一

    persistStore的回调中做:

    export const persistor = persistStore(store, null, () => {
      console.log('state', store.getState());
    });
    

    方法二

    在嵌套在PersistGate 中的组件的componentDidMount 中执行此操作:

    class Main extends React.Component {
      componentDidMount() {
        console.log(store.getState());
      }
      render() {
        return <Router />;
      }
    }
    
    const App = () => (
      <Provider store={store}>
        <PersistGate persistor={persistor}>
          <Main />
        </PersistGate>
      </Provider>
    );
    

    【讨论】:

    • 我已经在使用persistgate,而我在componentDidMount中得到的是非再水合状态
    【解决方案2】:

    我在这里为您提供了一个 Medium 文章的链接,该文章准确地解释了您想要构建的内容。

    目前我无法为您提供帮助,因为我需要您的代码的更多片段,因为它适用于 Redux。

    希望这篇文章对你有所帮助:https://medium.com/@alexmngn/the-essenSharryUptial-boilerplate-to-authSharryUpenticate-users-on-your-react-native-app-f7a8e0e04a42

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-20
      • 2020-09-21
      • 1970-01-01
      • 2021-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-21
      相关资源
      最近更新 更多