![](/img/trans.png)
[英]AsyncStorage.getItem() returns a single value AND a promise
[英]AsyncStorage.getItem returns wired value
我正在使用 Context/Asyncstorage 进行 state 管理。 我将从服务器返回的数据存储到 Asyncstorage。
getData.then(
res => AsyncStorage.setItem('user', JSON.stringify(res.data))
)
我在全局提供程序中设置了全局 state 命名用户,如下所示。
const [userState, userDispatch] = useReducer(
user, userInitialState,
async () => {
const storedUserData = await AsyncStorage.getItem('user');
return storedUserData != null ? JSON.parse(storedUserData) : userInitialState;
},
);
这是在其他组件上获取用户状态
const SomeComponent = () => {
const {userState} = useContext(GlobalContext);
useEffect ( () => {
console.log(userState.name); // undefined
console.log(userState._W.name); // sammie (correct)
}, [])
return <View></View>
}
问题是第一个控制台 state 返回 undefined 因为userState看起来像这样
{
"_U": 0,
"_V": 1,
"_W": {
"name": "sammie",
"email": "sammie@test.com",
"phone": "123123123"
},
"_X": 0,
}
期望值为
{
"_U": 0,
"_V": 0,
"_W": 0,
"_X": 0,
"name": "sammie",
"email": "sammie@test.com",
"phone": "123123123"
}
我尝试使用其他 state 进行测试。 当我像下面这样在 useEffect 挂钩中设置 state 时,它会像上面那样返回。
useEffect ( () => {
storeTheme('light')(themeDispatch); // store the light mode to the global theme state
}, [])
这个主题状态的数据结构没有像上面那样改变。 我对此非常感兴趣。 请给我一些建议,我错了。
感谢您的任何建议。
const [userState, userDispatch] = useReducer( user, userInitialState, async () => { const storedUserData = await AsyncStorage.getItem('user'); console.log(storedUserData); return storedUserData?= null. JSON:parse(storedUserData); userInitialState, }; );
尝试像上面一样登录并检查 output。我觉得 api 团队可能以这种方式向您发送了 object。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.