简体   繁体   English

使用 API 返回的记录更新状态,更新后

[英]Update State with record returned from API, after being updated

I'm currently trying to learn react and I'm struggling with the correct way to update a record within the state after its changes have been saved and returned via an API, so far the only way I can get it to work is by returning the entire list of records and updating the state with the new list through the reducer.我目前正在尝试学习反应,并且在保存更改并通过 API 返回后,我正在努力寻找在状态内更新记录的正确方法,到目前为止,我可以让它工作的唯一方法是返回整个记录列表并通过reducer用新列表更新状态。 Which is not ideal as I don't want to have to reload multiple records for one record's changes.这并不理想,因为我不想为一个记录的更改重新加载多个记录。

The Reducer code below currently adds the updated record onto the end of the state's data rather than replacing the existing record.下面的 Reducer 代码当前将更新的记录添加到状态数据的末尾,而不是替换现有记录。

        case 'EDIT_AUTHOR': 
            return {
                ...state,
                authors: [...state.authors, action.payload]
            }

This is the States Update Function这是状态更新功能

    // Edit Author
    async function editAuthor(author) {
        const config = {
            headers: {
                'Content-Type': 'application/json'
            }
        }

        try 
        {
            const res = await axios.put('api/v1/authors', author, config);

            dispatch({
                type: 'EDIT_AUTHOR',
                payload: res.data.data
            });
        } 
        catch (err) 
        {
            dispatch({
                type: 'AUTHORS_ERROR',
                payload: err.response.data.error
            });
        }
    }

Thanks in advance for any advice and please do let me know if you would like to see any more of the code, I think I have provided everything that is needed.提前感谢您的任何建议,如果您想查看更多代码,请告诉我,我想我已经提供了所需的一切。

when the ather has an id you can identify the user by that.当 ather 有一个 id 时,您可以通过它来识别用户。 As map returns a new array there is no need for spreading the old author list.当 map 返回一个新数组时,不需要传播旧的作者列表。

case 'EDIT_AUTHOR': {
    const updatedAuthor = action.payload;
    const authors = state.authors.map(author => updatedAuthor.id === author.id ? updatedAuthor : author);

            return {
                ...state,
                authors,
            }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM