我有一个名为故事的州 我在每个故事中有一个公寓的列表,在每个公寓里都有一个区域的列表强>。我正在尝试在公寓中添加一个新区域,但它替换现有数据。 这是显示我如何在故事中添加公寓详细信息的代码
let story = stories.find((story) => story.sid == storyID);
const storyWithDetails = {
...story,
appartmentDetails: [
...story.appartmentDetails,
{
apartment_name: apratmentName,
apartment_num: apratmentNum,
apartment_type: apartmentType,
areaDetails: [],
},
],
};
const otherStoris = stories.filter((story) => story.sid != storyID);
const newStories = [...otherStoris, storyWithDetails];
newStories.sort((a, b) => parseInt(a.sid) - parseInt(b.sid));
setStories(newStories);
现在我正在尝试通过以下代码添加该区域,但它正在替换该区域而不是添加新区域。如何解决这个问题?
let story = stories.find((story) => story.sid == storyIndex);
let apartment = story.appartmentDetails.find(
(apartment) => apartment.apartment_num == apartmentID
);
let apartmentWithArea = {
...apartment,
areaDetails: [
...apartment.areaDetails,
{
area_name: areaName,
areaImages: "",
},
],
};
console.log(apartmentWithArea);
编辑
如果我尝试像这样初始化状态
const [stories, setStories] = useState([
{
name: "1st Story",
sid: 1,
appartmentDetails: [
{
apartment_name: "Dummy",
apartment_num: "1",
apartment_type: "",
areaDetails: [{ area_name: "Bath", areaImages: "" }],
},
],
},
]);
并尝试添加新区域 apartmentWithArea 工作正常,但如果我想添加第三个区域 apartmentWithArea 替换第二个区域。