问题描述
setState 在 React Native 的 AsyncStorage 中不起作用.
setState not working inside AsyncStorage in React Native.
constructor(props) {
super(props);
this.state = {userId: ''};
}
componentDidMount() {
AsyncStorage.getItem('USER_ID', (err, result) => {
if (!err && result != null) {
this.setState({
userId: result
});
}
else {
this.setState({
userId: null
});
}
});
alert(this.state.userId);
let userId = this.state.userId;
fetch('http://localhost/JsonApi/myprofile.php', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
userId: userId,
}),
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({userDetails: responseJson});
})
.catch((error) => {
console.error(error);
});
}
使用 setState
和 alert 设置 userId
值根本不返回任何值.尝试了 Stackoverflow 的其他解决方案,但不符合我的预期.
Setting the userId
value using setState
and alert returns no value at all. Tried other solutions from Stackoverflow but not as per my expectation.
注意:代码已更新.从 AsyncStorage 获取 userId 后,会传递给 fetch.此处缺少 userId 值.
Note: Code updated. After getting userId from AsyncStorage, it will be passed to fetch. Here, userId value is missing.
推荐答案
2 种方法来做到这一点.一种是简单的,但另一种是根据反应推荐的正确方法
这里有一个 - 直接将值传递给状态.
One is here- pass value to state directly.
.then((responseJson) => {
// this.setState({userDetails: responseJson});
this.state.userDetails=responseJson;
this.setState({}); //for update render
})
第二条路来了
在渲染函数中检查状态值像这样.如果 UserDetails 状态为空,则每当 userDetails 状态获取数据渲染再次执行并提供完美结果时,它不会给您错误.
in the render function Check state Value like this .if UserDetails state is null it will be not give you error whenever userDetails state get data render execute again and provide perfect result.
render() {
return (
<div>
{this.state.userDetails ?
this.state.userDetails.map((data, index) =>
<tr key={index}>
<td>{data.userName}</td>
<td>{data.userEmail}</td>
</tr>
)
: null
}
</div>)}
让我知道收获.如果遇到问题
这篇关于setState 在 AsyncStorage 中无法在本机反应中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!