英文:
How do I use React setState() to set the state to a specific value that is a constant?
问题
const [number, setNumber] = useState(0);
let newNumber = 200;
useEffect(() => {
setNumber(number + 1);
}, [])
我相信我对React.js中状态如何工作有一些误解。如果我将上述代码中的setNumber(number + 1)
部分更改为+ 1
,如下所示,那么number
会变成201
,但如果我将其更改为= newNumber
,我会收到TypeError: Assignment to constant variable
错误。为什么会这样?而且,既然newNumber
没有使用const
标记,错误不应该是其他什么吗?
英文:
const [number, setNumber] = useState(0);
let newNumber = 200;
useEffect(() => {
setNumber(number = newNumber);
}, [])
I believe I'm misunderstanding something about how state works in React.js. If I set the above code's setNumber(number + 1) section to '+ 1' like so then number becomes '201' but if I set it to '= newNumber' I get a 'TypeError: Assignment to constant variable' error. Why is this the case? And shouldn't the error be something else since newNumber isn't a constant variable using the 'const' tag?
答案1
得分: 2
setNumber
函数接受一个你想要设置为状态的值。所以,如果你想将数字设置为新数字的值,你可以这样做:setNumber(newNumber)
。
英文:
The setNumber
function accepts a value you want to set your state to. So If you want to set number to the value of newNumber you would do setNumber(newNumber)
答案2
得分: 0
只需像这样使用setNumber:
useEffect(() => {
setNumber(newNumber);
}, [])
或者更好地在初始表达式中使用:
const [number, setNumber] = useState(200)
英文:
Just use setNumber like
useEffect(() => {
setNumber(newNumber);
}, [])
or better just in initial expression
const [number, setNumber] = useState(200)
答案3
得分: 0
只需将您的值放入 setNumber
函数中。
const [number, setNumber] = useState(0);
let newNumber = 200;
useEffect(() => {
setNumber(newNumber);
}, [])
英文:
Just put your values inside setNumber
function.
const [number, setNumber] = useState(0);
let newNumber = 200;
useEffect(() => {
setNumber(newNumber);
}, [])
答案4
得分: 0
useState
描述了状态,它可以是一个对象、字符串、布尔值和数字。如果它是一个原始数据,而不是一个对象,你只需要在更新时传递值,如下所示:
setStateVal(5); // 这里的5将成为新的状态
如果你的状态是一个对象,你需要按照以下方式传递更新后的状态对象:
setStateVal({ val: 5 });
无论如何,都不要使用=
运算符。
英文:
useState
describe the state, it can be an object, string, boolean and a number. In case its a primitive data i.e not an object, you just need to pass the value while updating it as follows:
setStateVal(5); // here 5 will become the new state
In case your state is an object, you need to pass the updated state object as follows:
setStateVal({val: 5});
In no case you use =
operator.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论