从React的useState挂钩中更改状态 [英] Mutating state from React's useState hook
问题描述
是的,为什么从React的新useState挂钩中改变状态是一个坏主意?我没有找到有关该主题的信息.
Is it, and why is it a bad idea to mutate a state from React's new useState hook? I found no info on the topic.
考虑以下代码:
const [values, setValues] = useState({})
// doSomething can be called once, or multiple times per render
const doSomething = (name, value) => {
values[name] = value
setValues({ ...values })
}
请注意值的突变.由于每个渲染可以多次调用doSomething,因此由于setState的异步属性而无法执行此操作:
Note the mutation of values. Since doSomething can be called more than once per render, doing this would not work because of the async properties of setState:
const doSomething = (name, value) => {
setValues({ ...values, [name]: value })
}
在这种情况下,直接改变值的方法是否正确?
Is the approach of mutating values directly the correct one in this case?
推荐答案
您永远不要直接更改状态,因为如果使用相同的对象引用更新状态,它甚至可能不会导致重新渲染.
You should never mutate state directly as it might not even cause a re-render if you update the state with the same object reference.
const { useState } = React;
function App() {
const [values, setValues] = useState({});
const doSomething = (name, value) => {
values[name] = value;
setValues(values);
};
return (
<div onClick={() => doSomething(Math.random(), Math.random())}>
{JSON.stringify(values)}
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>
您可以将函数作为 setValues
的第一个参数,就像您在类组件 setState
中所习惯的那样,然后该函数将获得正确的状态,如下所示:参数,返回的状态将是新状态.
You can give a function as first argument to setValues
just like you are used to in the class component setState
, and that function in turn will get the correct state as argument, and what is returned will be the new state.
const doSomething = (name, value) => {
setValues(values => ({ ...values, [name]: value }))
}
const { useState } = React;
function App() {
const [values, setValues] = useState({});
const doSomething = (name, value) => {
setValues(values => ({ ...values, [name]: value }));
};
return (
<div onClick={() => doSomething(Math.random(), Math.random())}>
{JSON.stringify(values)}
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>
这篇关于从React的useState挂钩中更改状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!