Javascript setState在react native中的异步存储中不工作?
setState在React Native中的异步存储中不工作Javascript setState在react native中的异步存储中不工作?,javascript,react-native,Javascript,React Native,setState在React Native中的异步存储中不工作 constructor(props) { super(props); this.state = {userId: ''}; } componentDidMount() { AsyncStorage.getItem('USER_ID', (err, result) => { if (!err && result != null) { this.s
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
设置userId
值并发出警报时,不会返回任何值。尝试了Stackoverflow的其他解决方案,但没有达到我的预期
注意:代码已更新。从AsyncStorage获取用户ID后,它将被传递到fetch。这里缺少userId值。我不知道您为什么编写这么多代码 第一条路
- 您不需要同时检查
和错误
,因为如果该值为null,则在状态中设置userId null。因此,您可以直接将结果
值设置为state
userId
- 还要设置一个日志以查看异步存储用户标识的输出
- 还请确认您正在某个地方设置“用户ID”中的值
const getUserId = async () => {
try {
const userId = await AsyncStorage.getItem('USER_ID') || 'none';
} catch (error) {
// Error retrieving data
console.log(error.message);
}
return userId;
}
你可以用
this.setState ({
userId : getUserId()
});
我不喜欢这种方式,因为我需要用async
和wait
关键字创建另一个方法。
我用第一种方式这样做。
更新
在getIten()中执行与userId相关的工作
,因为您在调用AsyncStorage
后立即通知用户ID。而AsyncStorage
在调用alert
后返回值
AsyncStorage.getItem("USER_ID").then((value) => {
console.log("userId in async = " + value);
this.setState({
userId: value
});
alert(this.state.userId); // move this line here
});
// removed from here
我不知道你为什么写这么多代码 第一条路
- 您不需要同时检查
和错误
,因为如果该值为null,则在状态中设置userId null。因此,您可以直接将结果
值设置为state
userId
- 还要设置一个日志以查看异步存储用户标识的输出
- 还请确认您正在某个地方设置“用户ID”中的值
const getUserId = async () => {
try {
const userId = await AsyncStorage.getItem('USER_ID') || 'none';
} catch (error) {
// Error retrieving data
console.log(error.message);
}
return userId;
}
你可以用
this.setState ({
userId : getUserId()
});
我不喜欢这种方式,因为我需要用async
和wait
关键字创建另一个方法。
我用第一种方式这样做。
更新
在getIten()中执行与userId相关的工作
,因为您在调用AsyncStorage
后立即通知用户ID。而AsyncStorage
在调用alert
后返回值
AsyncStorage.getItem("USER_ID").then((value) => {
console.log("userId in async = " + value);
this.setState({
userId: value
});
alert(this.state.userId); // move this line here
});
// removed from here
更新状态后尝试发出警报。一旦状态更新,您将得到回调
this.setState({
userId: result
},function(){
console.log("userId in async = ", this.state.userId);
alert(this.state.userId);
});
更新状态后尝试发出警报。一旦状态更新,您将得到回调
this.setState({
userId: result
},function(){
console.log("userId in async = ", this.state.userId);
alert(this.state.userId);
});
有两种方法可以做到这一点。根据react建议,一种方法简单,另一种方法正确 一个是这里-直接将值传递给state
.then((responseJson) => {
// this.setState({userDetails: responseJson});
this.state.userDetails=responseJson;
this.setState({}); //for update render
})
第二条路在这里
在呈现函数中,检查如下状态值。如果UserDetails状态为null,则每当UserDetails状态获取数据时,将不会给您错误。再次执行呈现并提供完美的结果
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>)}
render(){
返回(
{this.state.userDetails?
this.state.userDetails.map((数据,索引)=>
{data.userName}
{data.userEmail}
)
:null
}
)}
让我知道你的收获。如果面临问题有两种方法。根据react建议,一种方法简单,另一种方法正确 一个是这里-直接将值传递给state
.then((responseJson) => {
// this.setState({userDetails: responseJson});
this.state.userDetails=responseJson;
this.setState({}); //for update render
})
第二条路在这里
在呈现函数中,检查如下状态值。如果UserDetails状态为null,则每当UserDetails状态获取数据时,将不会给您错误。再次执行呈现并提供完美的结果
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>)}
render(){
返回(
{this.state.userDetails?
this.state.userDetails.map((数据,索引)=>
{data.userName}
{data.userEmail}
)
:null
}
)}
让我知道你的收获。如果遇到问题是否确定,则会触发回调。此外,设置状态更改可能不会立即反映出来。我看到您稍后试图提醒该值。这可能没有帮助。有时异步存储需要时间来执行,并且可能在异步存储执行之前调用了您的状态。因此,对于render方法中的调试console.warn(“check state”,this.state.userId)。(因为每次状态更改时渲染都会调用。)请尝试此操作,然后让我know@anilsidhu让我检查一下。我也这么想。但是,没有找到纠正的方法。@anilsidhu是的。它起作用了。但问题是,我想通过fetch发送这个userId。在获取时,它不会获取此值。并使用空值发送POST。我如何解决这个问题呢?为了更好的代码格式,我正在回答这个问题。你确定吗,回调被触发了。此外,设置状态更改可能不会立即反映出来。我看到您稍后试图提醒该值。这可能没有帮助。有时异步存储需要时间来执行,并且可能在异步存储执行之前调用了您的状态。因此,对于render方法中的调试console.warn(“check state”,this.state.userId)。(因为每次状态更改时渲染都会调用。)请尝试此操作,然后让我know@anilsidhu让我检查一下。我也这么想。但是,没有找到纠正的方法。@anilsidhu是的。它起作用了。但问题是,我想通过fetch发送这个userId。在获取时,它不会获取此值。并使用空值发送POST。我如何解决这个问题呢?为了更好的代码格式,我正在回答这个问题。没有必要使用基于promise的API。官方API也支持回调@Khemraj以前是第一个打成平局的。它不起作用了。在异步存储执行之前调用状态。不工作是什么意思?您可以提供您得到的信息,日志中是否有错误?不必使用基于promise的API。官方API支持callbac