reactjs - 单击项目覆盖另一个数据
问题描述
我有这个应用程序,用户可以在其中留下他们的评论并对特定的汽车进行评分。
https://codesandbox.io/s/public-antd-modal-forked-hj6bh?file=/App.js
现在存在一个问题,当用户首先输入一条消息,然后在点击星号后点击开始评分输入中的文本消失,但 id 不应清空输入,这应该仅在单击OK
按钮后
const setRate = (category, rate) => {
const newData = [...data];
let index = newData.findIndex((c) => c.carCat === category);
newData[index] = Object.assign(newData[index], { rate });
setData(newData);
};
const setSingleComment = (category, comment) => {
comments[category] = comment;
setComments(comments);
};
function handleOk() {
const newData = [...data];
for (let category of Object.keys(comments)) {
let index = newData.findIndex((c) => c.carCat === category);
newData[index].comments.push(comments[category]);
}
setData(newData);
setComments({});
setVisible(false);
}
为什么会发生以及如何解决这个问题?
解决方案
更新作为对象或数组的状态,应始终在顶层返回一个新引用,否则 react 将不会在对象中看到“更改”(它使用浅检查)并且您的组件不会重新渲染。
const setSingleComment = (category, comment) => {
comments[category] = comment;
setComments({ ...comments }); //a new object needs to be created here, otherwise react wont rerender.
};
坚持将状态保存在一个地方。在这种情况下,在顶层。这意味着从SetData
组件中删除状态,并简单地传递其值,并实现突变方法。
function SetData({ rate, singleComment, onRateChange, onSingleCommentChange }) {
//only need to store state in a single place. In this case, at the app level
const handleRateChange = (e) => {
onRateChange(e);
};
function handleCommentChange(e) {
const text = e.target.value;
onSingleCommentChange(text);
}
return (
<div>
<Rate value={rate} onChange={handleRateChange} />
<input
value={singleComment ? singleComment : ""}
onChange={handleCommentChange}
/>
</div>
);
}
在CodeSandbox上查看更新的代码
我希望我已经意识到你的意图。
推荐阅读
- tensorflow - Tensorflow lite 微神经网络层构建
- arrays - OpenCL:数组大小与工作项全局大小之间的关系
- android - 使用 NavHostFragment 显示 DialogFragment 显示为空
- javascript - 防止 Redux 重新渲染整个树并清除本地状态
- ping - 防火墙阻止ping时如何通过扫描本地网络获取mac地址
- javascript - 如何从 html 中的谷歌云存储中获取 json 文件的内容
- node.js - 在 Windows 上设置 node.js 以与 p5.js 一起使用“未捕获的 ReferenceError:未定义 cd”
- javascript - 如何在 Vue 的 v-for 循环中使用数组映射?
- asp.net - 如何将单独的 css 文件链接到 aspx 文件
- mysql - 从当前月份开始获取 mySQL 中的按月记录数