【问题标题】:How to read redux store from non React components?如何从非 React 组件中读取 redux 存储?
【发布时间】:2017-02-06 16:55:11
【问题描述】:

我正在使用redux 构建我的第一个react native 应用程序。

我的store配置如下

function configureStore(onComplete: ?() => void) {
  const store = autoRehydrate()(createMyAppStore)(reducers);
  persistStore(store, {storage: AsyncStorage}, onComplete);
  if (isDebuggingInChrome) {
    window.store = store;
  }
  return store;
}

我有一个认证action如下

export function authentiate(credentials) {
  return (dispatch) => {
    return LoginApi.authenticate(credentials)
    .then(response => {
      return response.json().then(function(json) {
          dispatch(onAuthSuccess(json));
      });
    })
    .then(response => { dispatch(getUserInfo()); })
    .catch(error => {
      throw(error);
    });
  };
}

我的getUserInfoaction如下

export function getUserInfo() {
  return (dispatch) => {
    return LoginApi.gerUserInfo()
    .then(result => { dispatch(onGetUserInfoSuccess(result.json())); })
    .catch(error => {
      throw(error);
    });
  };
}

我的认证reducer如下

function auth(state: State = initialState, action: Action): State {
  switch (action.type) {
    case types.AUTH_SUCCESSFUL :
    return [...state, Object.assign({}, action.auth)];
    default :
    return state;
  }
  return state;
}

LoginApi 是一个简单的 ES6 类。 getUserInfo 需要access token 等详细信息以及从LoginApi.authenticate 调用中获得的其他参数。

如何从non-react 组件中读取来自redux store 的身份验证信息?

【问题讨论】:

    标签: react-native redux react-redux


    【解决方案1】:

    redux-thunk 的第二个参数是getState

    export function getUserInfo() {
      return (dispatch, getState) => {
        const state = getState() // or cherry pick what you need
        return LoginApi.gerUserInfo(state)
        .then(result => { dispatch(onGetUserInfoSuccess(result.json())); })
        .catch(error => {
          throw(error);
        });
      };
    }
    

    https://github.com/gaearon/redux-thunk#composition

    这只是stores 自己的getState 函数。

    http://redux.js.org/docs/api/Store.html#getState

    您可以导出/导入您的store 并根据需要直接调用getState。

    let store = createStore(...)
    export { store }
    
    // anywhere.js
    import { store } from './your-store.js'
    let state = store.getState()
    

    【讨论】:

    • 这是否意味着我无法从任何非反应组件访问存储/状态。相反,我应该从操作中访问它们并将它们作为参数传递给外部组件?
    • 如果您导出您的store(您使用createStore() 创建的那个),您可以将其导入任何您想要的位置并调用store.getState()。不必是组件。但是,您的示例使用的是已经可以访问商店的 redux-thunk。这取决于你
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-02
    • 2018-01-21
    • 2016-12-25
    • 2018-09-29
    • 2021-03-01
    • 1970-01-01
    相关资源
    最近更新 更多