在axios呼叫之后,我该如何更新前端? [我有两种方式]

时间:2018-05-20 05:06:26

标签: reactjs state axios

我有一系列待办事项。当我删除其中一个时,我也使用DELETE调用从数据库中成功删除它。但是,我不确定如何更新前端。第一种方法是通过删除相关的待办事项来改变状态。

onDelete(todo) {
    axios.delete('api/todos/' + todo.id).then(res => {
        var array = [...this.state.todos]; // make a separate copy of the array
        var index = array.indexOf(todo)
        array.splice(index, 1);
        this.setState({todos: array}); // other state elemenets other than todos will not be affected
    });
}

其他方式是,制作新的axios GET请求以从数据库获取所有待办事项。 (这将是axios请求中的axios请求)

onDelete(todo) {
    axios.delete('api/todos/' + todo.id).then(res => {
        // make an axios get request on api/todos
        // then, set state with data in response.
    });
}

因此,哪一种方法更好?

1 个答案:

答案 0 :(得分:0)

最好的方法是第二个,再次调用get请求。因此,无论更改数据库经历了什么,UI都将是来自db的数据的精确副本,而不是从UI手动更改(在此情况下删除)列表。但是,在这种情况下,UI更新的api响应会有延迟。