react-native - 如何从 native AsyncStorage 中填充 Redux 中的初始状态?

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

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

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

最佳答案

这是我想出的解决方案。只需创建一个获取 AsyncStorage 属性的操作,并将属性数组分派(dispatch)给将它们分配给状态的 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());
然后在 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);

关于react-native - 如何从 native AsyncStorage 中填充 Redux 中的初始状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53074761/

相关文章:

javascript - 在 React-Native 中使用另一个文件进行 Realm 查询

ios - react native ListView 添加项目不起作用

javascript - ngrx - 一旦分派(dispatch)的操作成功更新商店,如何执行操作?

redux - 重新选择 - 创建一个仅用于获取部分状态的内存选择器是否有意义?

javascript - 获取 promise 数组中的值

reactjs - 重构 AutoHeightWebView 库以获取在单独的浏览器中打开的超链接

android - 应用程序 :installDebug Task while attempting to run react-native app on MI MAX 2 android device 期间的 SecurityException

redux - 我应该为 angular8 应用程序使用哪个状态管理库?

reactjs - 如何将 React 中的 localStorage 代码转换为 React Native 中的 AsyncStorage?

react-native - React Native 的 AsyncStorage 可能失败的案例有哪些?