使用React的setState()方法将状态设置为一个常量值的方法是什么?

huangapple go评论81阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年1月3日 20:44:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/59578882.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定