首页 > 解决方案 > 我想使用 expo AsyncStorage 将商店持久化到 redux 但我收到错误

问题描述

我想将我的商店保留在 AsyncStore 中。我在创建商店之前获取了我的 initialState。但它不会等待获取数据并给出错误“传递给 createStore 的 preloadedState 参数具有意外类型的 'Object'”。

这是我的 loadState 函数

export const _loadState = async () => {
  try {
    const serializedState = await AsyncStorage.getItem('store');
    if (serializedState === null) {
      return undefined;
    }

    return JSON.parse(serializedState);
  } catch (error) {
    return undefined;
  }
};

这是我的商店

const initialState = _loadState();

const store = createStore(reducers, initialState);

我希望承诺必须在 createStore() 之前解决,但它没有解决。英语不是我的主要语言,所以如果有不明白的地方请告诉我。谢谢

标签: javascriptreact-nativeexpo

解决方案


const initialState = await _loadState();

您可以使用 await 确保它在它之前 100% 解决。

在这里使用 try catch 处理错误情况


推荐阅读