7

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

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

2 回答 2

11

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

然后在屏幕文件中,您可以使用 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);
于 2018-10-31T05:35:43.300 回答
0

Aman Mittal 为使用packageAsyncStorage将状态持久化和填充初始状态提供了极好的指南。redux-persist

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),
);
于 2021-04-17T02:26:13.313 回答