如何使用react hook react.js一次更新多个状态

Web*_*per 14 javascript setstate reactjs react-hooks

我想知道我是否可以在同一个函数中多次使用 setState 钩子。例如,像这样

import React, { useEffect, useState } from 'react';

function(props) {
const [color, setColor] = useState(0)
const [size, setSize]= useState(0)
const [weight, setWeight] = useState(0)

const onClickRandomButton = () => {
    setColor(Math.random() * 10)
    setSize(Math.random() * 10)
    setWeight(Math.random() * 10)
}

return <div>
  <button onClick = {onClickRandomButton}>random</button>
</div>

}
Run Code Online (Sandbox Code Playgroud)

我已经测试过了,但它没有按预期工作。使用钩子一次设置多个值,我该怎么办?谢谢

小智 12

您可以使用一个带有对象值的 useState 来一次更新样式:

import React, { useEffect, useState } from 'react';

export default function (props) {
  const [style, setStyle] = useState({ color: 0, size: 0, weight: 0 });

  const onClickRandomButton = () => {
    setStyle({
      color: Math.random() * 10,
      size: Math.random() * 10,
      weight: Math.random() * 10,
    });
  };

  return (
    <div>
      <button onClick={onClickRandomButton}>random</button>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

如果在任何方法中您只想更新一个属性,例如:颜色,您可以执行以下操作:

...
  const handleEditColor = color => {
    setStyle({
      ...style,
      color
    });
  };
...
Run Code Online (Sandbox Code Playgroud)