如何从 React Native 的 AsyncStorage 填充 Redux 中的 initialState?

Ste*_*rey 7 react-native redux asyncstorage react-native-web

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

const initialState = {
  uid: "",
  username: "",
};
Run Code Online (Sandbox Code Playgroud)

Ste*_*rey 11

这是我想出的解决方案。只需创建一个获取 AsyncStorage 属性的操作,并将属性数组分派给将它们分配给状态的 reducer。您可以直接在商店上调用该操作。比添加整个其他库要轻得多。为简单起见,我假设所有 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());
Run Code Online (Sandbox Code Playgroud)

然后在 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);
Run Code Online (Sandbox Code Playgroud)