Axios.put ReactJS

问题描述 投票:0回答:1

它有点工作,但问题是它复制了正在更新的文件,并把它放在页面的最后,我想做的是在项目上显示更新。

我想做的是

    submitEdit = (id, value) => {
    let {todos} = this.state
    todos.map((item => {
        if (item._id === id) {
            axios
                .put(`http://localhost:8080/edit/${id}`, {
                    todo: value,
                })
                .then((res) => {
                    this.setState({
                        todos:[...todos,{todo:value}]
                    })
                    console.log("res", res);
                })
                .catch((err) => {
                    console.log("err", err);
                });
        }
    }))
}

除此之外,一切正常

javascript reactjs axios
1个回答
2
投票

你需要通过使用索引来更新状态,这样todo元素才会被更新,而不是复制并添加到页面末尾

您可以使用 Array.prototype.slicespread syntax 以此

todos.map(((item, i) => {
    if (item._id === id) {
        axios
            .put(`http://localhost:8080/edit/${id}`, {
                todo: value,
            })
            .then((res) => {
                this.setState({
                    todos:[...todos.slice(0, i),{todo:value}, ...todos.slice(i + 1)]
                })
                console.log("res", res);
            })
            .catch((err) => {
                console.log("err", err);
            });
    }
}))
© www.soinside.com 2019 - 2024. All rights reserved.