如何在不刷新的情况下链接同步请求



首先,我从远程端点加载用户数据,并在此方法中设置componentDidMount状态:

componentDidMount() {
axios
.get("http://localhost:8080/api/users")
.then(res => {
const users = res.data.map(obj => obj);
this.setState({ data: users });
})
} 

然后,我将带有 POST 请求的用户添加到 API,我想从远程端点加载新用户数据并再次设置状态,以便看到显示的新添加:

addUser = () => {
var currentThis = this;
axios
.post("http://localhost:8080/api/users", {
Name: this.Name.inputRef.value,
Surname: this.Surname.inputRef.value,
})
.then(res => {
const status = res.data.status;
if (status === 'OK'){
axios
.get("http://localhost:8080/api/users")
.then(res => {
const users = res.data.map(obj => obj);
currentThis.setState({ data: users });
})
}
else{
//error
}
})
}

回调中的请求.then函数始终在发布新用户之前响应用户。所以状态不会改变,我必须重新加载页面才能显示新的添加内容。

如何在不重新加载页面的情况下更新或呈现响应?

也许您可以使用 setState() 的回调来发出第二个 AJAX 请求? 像这样:

addUser = () => {
var currentThis = this;
axios
.post("http://localhost:8080/api/users", {
Name: this.Name.inputRef.value,
Surname: this.Surname.inputRef.value,
})
.then(res => {
const status = res.data.status;
if (status === 'OK'){
const users = res.data.map(obj => obj);
currentThis.setState({ data: users }, function() {
axios.get("http://localhost:8080/api/users")
}
});
else{
//error
}
})
}

有关 setState() 函数及其回调参数的更多信息

如果您是这些 API 的作者,则应在成功的 POST 请求时返回更新的用户列表或新用户本身。然后,您可以使用响应进行setState

如果您无法控制 API,并且既然您确定status === 'OK'意味着已添加新用户,为什么还需要发出另一个 GET 请求?

只需将新创建的对象添加到data状态,然后设置状态:

if (status === 'OK'){
const updatedUsers = this.state.data.push(newUser)
this.setState({data: updatedUsers})
}

最新更新