如何在不刷新和处理API请求的情况下更新状态数组?
我有一个简单的React应用程序,可以获取数据并将其发布到API。称之为简单的待办事项应用程序。我正试图找出处理数据的最佳方式,即“反应”方式 我了解到最好的ajax调用位置是如何在不刷新和处理API请求的情况下更新状态数组?,api,reactjs,Api,Reactjs,我有一个简单的React应用程序,可以获取数据并将其发布到API。称之为简单的待办事项应用程序。我正试图找出处理数据的最佳方式,即“反应”方式 我了解到最好的ajax调用位置是componentWillMount或componentDidMount,但是在我的应用程序中,如果我使用componentWillMount或componentDidMount,我无法让它无缝地重新加载数据。我必须刷新页面才能看到新添加的内容。让我解释一下我的情况: ... constructor() {
componentWillMount
或componentDidMount
,但是在我的应用程序中,如果我使用componentWillMount或componentDidMount,我无法让它无缝地重新加载数据。我必须刷新页面才能看到新添加的内容。让我解释一下我的情况:
...
constructor() {
super();
this.state = {
todos: [],
todo: 'do this!'
};
...
getTodos(){
Client.getTodos((todos) => {
this.setState({todos})
});
};
postTodo(e){
let todo = this.state.todo;
Client.postTodo(todo, (todo) => {
this.setState({todos: this.state.todos.concat([todo])})
});
};
componentDidMount(){this.getTodos()}; //componentWillMount() works gives me similar effect
render (){
return (
<div>
<p>Hello from todos!</p>
<ul>
{this.state.todos.map((t, index) =>
<li key={index}>{t.description}</li>
)}
</ul>
<AddTodo todo={this.state.todo}
handleChange={this.handleChange}
postTodo={this.postTodo}
/>
</div>
...
//inside AddTodo.js
...
<input type="text" placeholder={this.props.todo} onChange={this.props.handleChange} />
<input type="button" value='submit' onClick={this.props.postTodo} />
这两种客户端方法都有效
我试图摆脱的一种行为是这样的——假设这是我目前的待办事项:
- Todo1
- Todo2
- Todo3
当我输入newtodo
时,比如说Todo4
,它会在我按下Submit之后立即显示出来
- Todo1
- Todo2
- Todo3
- //shows a new list, but it is empty
我需要刷新页面以查看列表上的Todo4
。允许我添加Todo4
而无需刷新页面的一种方法是:
...
render(){
this.getTodos();
return (
<div>
...
。。。
render(){
这个。getTodos();
返回(
...
回到SO帖子,它并不是在componentwillmount或componentdidmount中执行ajax请求
这感觉不像是“反应”方式。在处理API请求时,如何以正确的方式实时更新TODO列表(无需重新加载页面)?尝试将您的
postTodo
更改为
function postTodo(todo, cb){
return fetch(`api/todos`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
description: todo
})
}).then((response) => response.json())
.then(json => cb(json));
};
理想情况下,您应该检查响应中的状态代码,并仅在成功时更新
function postTodo(todo, successCb, errorCb){
return fetch(`api/todos`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
description: todo
})
}).then(response => {
let json = response.json();
// successCode = 201 for create resource
if (response.status != successCode) {
json.then(error => {
errorCb(error);
})
} else {
json.then(json => {
successCb(json);
})
}
});
function postTodo(todo, successCb, errorCb){
return fetch(`api/todos`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
description: todo
})
}).then(response => {
let json = response.json();
// successCode = 201 for create resource
if (response.status != successCode) {
json.then(error => {
errorCb(error);
})
} else {
json.then(json => {
successCb(json);
})
}
});