function Example() {
const [strings, setStrings] = useState(["hi","yo"]);
return (
<div>
<input name='foo' type="text" value={strings[0]} onChange={setElement} />
</div>
);
function setElement(e){
let copyStrings = strings;
copyStrings[0] = e.target.value;
setStrings(copyStrings)
}
}
当我在文本输入框中键入一个键时,我可以在react devtools中看到useState挂钩的状态已更新为包括该键,但是输入中显示的文本没有更改。为什么会这样,我该如何解决?
我有一个值数组,希望用户能够在输入控件中进行编辑。
答案 0 :(得分:1)
let copyStrings = strings
是浅表副本。您正在将引用复制到数组
您需要进行深层复制。有几个选项:
let copyStrings = [...strings]; //works with arrays
要么
let copyStirngs = JSON.parse(JSON.stringify(strings)); // works with objects as well