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

时间:2018-10-31 00:45:32

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

我有一个React Native应用。我将用户名和uid存储在AsyncStorage中,因此它们不必每次都登录。如何用这些值填充initialState。有一些软件包可以为您完成此操作,但似乎应该可以这样做,而无需其他软件包的开销。现在,初始状态只是空值。

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

2 个答案:

答案 0 :(得分:0)

这是我想出的解决方案。只需创建一个获取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());

然后在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);

答案 1 :(得分:0)

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