只更新一个对象键Reactjs



晚上好!我有一个对象,我正在向我的API发送一个PUT来更新图书信息。我希望能够只发送一个属性到API,并有其余的坚持。到目前为止,它们被设置为undefined,如果您只设置一个属性,则必须更新所有3个属性才能正常工作。下面的代码是可重用的组件,该组件是为存储在API中的每本书创建的。

Book.js

import React, { useState } from "react";
import {
deleteBook,
updateBook
} from '../api/books';
// Material UI
import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button';
import Stack from '@mui/material/Stack';
const Book = ({setBooks, bookId, bookTitle, bookStart, bookEnd}) => {
// State to update an existing books data
const [updateNewBookTitle, setNewUpdateBookTitle] = useState("");
const [updateNewBookStart, setNewUpdateBookStart] = useState("");
const [updateNewBookEnd, setNewUpdateBookEnd] = useState("");
// Delete a specific book
const onDeleteBook = async (id) => {
const responseStatus = await deleteBook(id);

if (responseStatus !== 200) {
alert("Deleting failed");
return;
}

setBooks((previousBooks) =>
previousBooks.filter((book) => book.id !== id)
);
};

// Update a previous book
const onUpdateBook = async (id, newTitle, newStart, newEnd) => {
const responseStatus = await updateBook(id, newTitle, newStart, newEnd);

if (responseStatus !== 200) {
alert("Updating failed");
return;
}

setBooks((previousBooks) => {
const nextBooksState = [...previousBooks];
const bookToUpdate = nextBooksState.find(
(book) => book.id === id
);

bookToUpdate.title = newTitle;
bookToUpdate.start = newStart;
bookToUpdate.end = newEnd;



return nextBooksState;
});
};

return (
<form onSubmit={() => {onUpdateBook(bookId, updateNewBookTitle, updateNewBookStart, updateNewBookEnd)}}>
<Stack key={bookId}>
<TextField id="standard-basic"
label="Title"
defaultValue={bookTitle}
variant="standard"
onChange={e => setNewUpdateBookTitle(e.target.value)}
/>
<TextField id="standard-basic"
label="Start Date"
defaultValue={bookStart}
variant="standard"
onChange={e => setNewUpdateBookStart(e.target.value)}
/>
<TextField id="standard-basic"
label="End Date"
defaultValue={bookEnd}
variant="standard"
onChange={e => setNewUpdateBookEnd(e.target.value)}
/>
<Button variant="contained"
color="success"
type="submit"
>
Update Book
</Button>
<Button variant="contained"
color="error"
onClick={() => {onDeleteBook(bookId)}}
>
Delete Book
</Button>
</Stack>
</form>

)
}
export default Book;

更新数据库将直接关系到您的后端功能。因为你想只发送一个属性或者不是完整信息的整个对象,所以你的服务器PUT请求应该处理那部分。我认为有两个选项可以达到你想要的:

  1. 将所有图书信息检索到组件中,并对同一对象中现有的更新数据发出PUT请求。
  2. 只发送更新的信息到您的服务器功能,并添加一个if/switch或任何其他条件的情况下,检查您的请求对象是否包含完整的数据列在数据库中。如果为false,则仍然获取相关的图书数据,使用扩展操作符并仅更新相关的键。例如:requestObject ={…existingBookData, updatedData}

我希望这是有意义的

相关内容

  • 没有找到相关文章

最新更新