我想知道是否可以在同一函数中多次使用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>
}
我已经测试过,但无法正常工作。要使用挂钩一次设置多个值,该怎么办?谢谢
您可以使用带有对象值的一个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>
);
}
并且如果在任何方法中您只想更新一个属性,例如:color,则可以执行以下操作:
...
const handleEditColor = color => {
setStyle({
...style,
color
});
};
...
我相信unstable_batchUpdates
既适用于钩子,也适用于基于类的组件。除了前缀unstable_
之外,Dan Abramov和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)
})