【问题标题】:How to get the id of the added item after a post request in react?发布请求后如何获取添加项目的ID?
【发布时间】:2018-05-31 17:00:18
【问题描述】:

我有一个函数,它接受两个输入并在反应中发出一个发布请求:

addNote(title, content){
    this.setState({title: title, content: content, error: ''}, () => {
        const newNote = {
            title: this.state.title,
            content: this.state.content,
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
        };
        fetch('http://localhost:8000/notes', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(newNote)
        })
        .catch(error => {
            this.setState({error: 'Error adding note.'});
            console.error('Error during adding note', error);
        })
        const storedNotes = this.state.notes;
        storedNotes.unshift(newNote);
        this.setState({notes: storedNotes});
        //Adding this.fetchNotes(); here does not work
    });
}

fetchNotes(){
    fetch('http://localhost:8000/notes')
    .then(response => response.json())
    .then(data => this.setState({isLoading: false, notes: data}))
}

注释的 id 类似于 5b0fac246637e1005ca0a7b5(由猫鼬给出)。如何在 react 中获取新添加项目的 id,以便我可以执行其他操作,例如更新和删除路由 /notes/:noteId 中的注释?当我添加注释并尝试删除它时,由于 id 未定义,出现 404 错误。在页面重新加载时,操作工作正常。我不想在服务器中发出 post 请求,因为视图是由 react 呈现的。

添加注释后,我再次尝试获取所有注释的请求。它不能按预期工作。添加的注释不会在提交时立即显示。

我是否应该自己发出一个带有 id 的帖子请求,比如 new Date().toISOString()?

【问题讨论】:

  • 除非您显示实际“添加”到数据库的实际“服务器”端代码,否则谁能知道该回答什么?前端实际上与此无关,因为它所做的只是要求后端做某事。所以你向我们展示了错误的代码。
  • @Neil Lunn,非常感谢。我在服务器中添加了行 data => res.send(data) 并且能够获取 id。

标签: reactjs mongoose crud


【解决方案1】:

为什么在 POST 请求后返回新的 mongoose id?

类似这样的:

addNote(title, content){
    this.setState({title: title, content: content, error: ''}, () => {
        const newNote = {
            title: this.state.title,
            content: this.state.content,
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
        };

        fetch('http://localhost:8000/notes', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(newNote)
        })
        .then(response => response.json())
        .then(data => {
            // here data.id might contain your objectId

            const storedNotes = this.state.notes;
            storedNotes.unshift(newNote);
            this.setState({notes: storedNotes});
            //Adding this.fetchNotes(); here does not work
        })
        .catch(error => {
            this.setState({error: 'Error adding note.'});
            console.error('Error during adding note', error);
        });
    });
}

fetchNotes(){
    fetch('http://localhost:8000/notes')
    .then(response => response.json())
    .then(data => this.setState({isLoading: false, notes: data}))
}

但这需要对服务器上的 /notes 端点进行一些重构。

【讨论】:

  • 非常感谢。我现在可以拿到身份证了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-24
  • 1970-01-01
  • 2022-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多