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

how to update multiple state at once using react hook react.js

我想知道是否可以在同一个函数中多次使用 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>

}

我已经测试过了,但没有达到预期的效果。 使用hook一次设置多个值,我该怎么办? 谢谢

您可以使用一个带有对象值的 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>
  );
}

如果在任何方法中您只想更新一个 属性,例如:颜色,您可以这样做:

...
  const handleEditColor = color => {
    setStyle({
      ...style,
      color
    });
  };
...

我相信 unstable_batchUpdates 适用于挂钩,也适用于基于 class 的组件。除了前缀 unstable_ 它被 Dan Abramov and in React-Redux docs 提到所以我认为使用它是安全的:

import { unstable_batchUpdates } from 'react-dom';
...

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