【问题标题】:How do I populate the initialState in Redux from react native's AsyncStorage?如何从 react native 的 AsyncStorage 填充 Redux 中的 initialState?
【发布时间】:2018-10-31 00:45:32
【问题描述】:

我有一个 React Native 应用程序。我将用户名和 uid 存储在 AsyncStorage 中,因此他们不必每次都登录。如何使用这些值填充 initialState。有一些包可以为你做这件事,但看起来这应该是可行的,而不需要另一个包的开销。现在初始状态只是空值。

const initialState = {
  uid: "",
  username: "",
};

【问题讨论】:

  • 你可以手动实现一个系统,在应用启动时从 AsyncStorage 重新水化你的 Redux 状态,但是像 redux 这样的库已经有了这个
  • 我对 React/Redux 还很陌生。我该怎么做?

标签: react-native redux asyncstorage react-native-web


【解决方案1】:

这是我想出的解决方案。只需创建一个获取 AsyncStorage 属性的操作并将属性数组分派到将它们分配给状态的减速器。您直接在商店中调用该操作。比添加整个其他库要轻得多。为简单起见,我假设所有 Redux 代码都在一个名为 myRedux.js 的文件中:

// Imports:
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { AsyncStorage, } from "react-native";

// Set initial state to empty values:
const initialState = {
  uid: "",
  username: "",
};

// Reducer: 
const reducer = (state = initialState, action) => {
  switch(action.type) {
    case "setInit":
      return { 
        ...state, 
        uid: action.uid,
        username: action.username,
      }

    default: 
      return state;
  }
};

// Store
const store = createStore(reducer, applyMiddleware(thunk));
export { store };

// Action
const setInit = (result) => {
  return {
    type: "setInit",
    uid: result[0][1],
    username: result[1][1],
  };
} 

const getAsyncStorage = () => {
  return (dispatch) => {
    AsyncStorage.multiGet(['uid', 'username'])
    .then((result) => {dispatch(setInit(result))});
  };
};

// Dispatch the getAsyncStorage() action directly on the store.
store.dispatch(getAsyncStorage());

然后在 Screen 文件中您可以使用 mapStateToProps 访问它们:

const mapStateToProps = (state) => {
  return {
    uid: state.uid,
    username: state.username,
  };
}

// Access the prop values in the render:
render() {
  return (
    <View>
      <Text>Uid: {this.props.uid}</Text> 
      <Text>Username: {this.props.username}</Text>
    </View>
  );
}

// Connect mapStateToProps to the component class
export default connect(mapStateToProps)(MyScreen);

【讨论】:

    【解决方案2】:

    Aman Mittal 为将状态持久化到 AsyncStorage 并使用 redux-persist package 填充初始状态提供了出色的指南。

    https://blog.jscrambler.com/how-to-use-redux-persist-in-react-native-with-asyncstorage/

    只要确保在到达config 部分时,您使用AsyncStorage 作为storage 值:

    import { persistReducer } from 'redux-persist';
    import rootReducer from './reducers';
    
    
    ...
    
    export const config = {
        key: 'my-root-key',
        storage: AsyncStorage,
        blacklist: [],
    };
    
    const store = createStore(
      persistReducer(
        config,
        rootReducer
      ),
      compose(...activeEnhancers),
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-31
      • 2019-02-20
      • 1970-01-01
      • 2023-02-08
      • 2021-01-10
      • 1970-01-01
      • 2019-11-03
      • 1970-01-01
      相关资源
      最近更新 更多