[英]Splice deleting last element of an array of object in react
我有在按钮单击时动态添加的文本字段,并根据状态变量 [inputList] 映射项目。 问题是当我尝试使用拼接或过滤选项删除字段时,它总是删除最后一个项目,但在控制台中显示它已删除我想要的特定项目,但在 UI 中它正在删除最后一个字段无论我删除哪个字段。 例如,如果有 3 个字段名为“A”、“B”和“C”。 如果我尝试删除 B,它会删除 B 但不会影响 UI。 在 UI 中,它只显示最后一个项目被删除,即 C 已被删除,但在控制台 B 已被删除。
这是我的代码:
<FormControl style={{ display: "flex", flex: 1 }}>
<FormGroup>
{inputList.map((x, i) => {
return (
<div key={i}>
<div className={styles.options}>
{!distributePoints ? (
<FormControlLabel
key={i}
value={x.isCorrect}
control={<Checkbox />}
checked={x.isCorrect}
onChange={(e) => handleIsCorrect(e, i)}
/>
) : (
""
)}
<div className="editor">
<BubbleEditor
handleAnswer={handleInputChange}
index={i}
theme="bubble"
/>
</div>
{distributePoints ? (
<TextField
variant="standard"
name="points"
InputProps={{
disableUnderline: true,
type: "number",
}}
value={x.points}
onChange={(e) => handlePointChange(e, i)}
className={styles.inputCounter}
/>
) : (
""
)}
{inputList.length !== 1 && (
<IconButton
onClick={() => handleRemoveClick(i)}
className={styles.icon}
>
<DeleteIcon
sx={{ fontSize: 24, color: "#3699FF" }}
/>
</IconButton>
)}
</div>
{inputList.length - 1 === i && (
<div
style={{
display: "flex",
justifyContent: "space-between",
}}
>
<button
onClick={handleAddClick}
type="button"
className={styles.addButton}
>
<img src={PlusSign} alt="" /> Add another answer
</button>
<div className={styles.label}>
<Checkbox
checked={shuffle}
onChange={handleShuffle}
style={{ color: "#00A3FF" }}
/>
Shuffle answer
</div>
</div>
)}
</div>
);
})}
</FormGroup>
</FormControl>
删除功能:
const handleRemoveClick = (index) => {
const list = [...inputList];
list.splice(index, 1);
setInputList(list);
};
添加功能:
const handleAddClick = () => {
setInputList([...inputList, { answer: "", isCorrect: false, points: 0 }]);
};
正在使用的对象的状态数组:
const [inputList, setInputList] = useState([
{ answer: "", isCorrect: false, points: 0 },
]);
在更新状态属性时,使用其先前的值,应使用回调参数。
这是由于状态更新可能具有异步性质
var handleRemoveClick = (index)=> {
setInputList((list)=> (
list.filter((o,i)=> (index != i))
);
};
var handleAddClick = ()=> {
setInputList((list)=> (
list.concat({answer:'', isCorrect: false, points: 0})
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.