代码之家  ›  专栏  ›  技术社区  ›  David Geismar

在应用程序初始化时从持久化存储中检索令牌

  •  1
  • David Geismar  · 技术社区  · 6 年前

    我已经在我的应用程序中插入了redux。当应用程序被终止后重新启动时,think Id想做的第一件事是在重新水化的存储中获取我的身份验证令牌,并检查令牌是否仍然有效。

    我正在努力找到一个好的策略来做到这一点。作为第一个直觉,我会尝试在componentDidMount方法的根应用程序组件中这样做。以下是我的组件:

    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);
    

    我怎样才能做到这一点?

    2 回复  |  直到 6 年前
        1
  •  3
  •   Roy Wang    6 年前

    方法1

    在你的记忆中做这件事 persistStore :

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

    方法2

    进去吧 componentDidMount 嵌套在 PersistGate :

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

    我在这里给你一个链接,指向一篇媒体文章,该文章准确地解释了你想要构建什么。

    我现在帮不了你,因为我需要更多的代码片段,因为它可以与Redux一起使用。

    希望本文能帮助您: https://medium.com/@alexmngn/the-essenSharryUptial-boilerplate-to-authSharryUpenticate-users-on-your-react-native-app-f7a8e0e04a42