在选择标签React中更新状态的困难
我有一个简单的应用程序来生成随机颜色。但这仅在下一个更改上更新,我无法弄清楚如何使更新函数正常工作。
const handleHueChange = (e) => {
const newHue = e.target.value;
setHueColor(newHue);
setColor(randomColor({ hue: hueColor, luminosity: lum }));
console.log(color, hueColor, lum);
};
有函数,这里的选择
<form>
<select
name="hue"
value={hueColor.value}
onChange={(e) => handleHueChange(e)}
>
{hue.map((hue, idx) => (
<option key={idx}>{hue}</option>
))}
</select>
</form>
,这里有一个链接到代码沙盒
https://codesandbox.io/s/brave-austin-ujv5xw?file=/src/app/app/app.js:1414-1673
使用效果是正确的值仅更新下一个渲染。
I have a simple app to Generate a Random color. But it only updates on the next change and I can't figure out how to get an updater function to work.
const handleHueChange = (e) => {
const newHue = e.target.value;
setHueColor(newHue);
setColor(randomColor({ hue: hueColor, luminosity: lum }));
console.log(color, hueColor, lum);
};
There is the function and here it the select
<form>
<select
name="hue"
value={hueColor.value}
onChange={(e) => handleHueChange(e)}
>
{hue.map((hue, idx) => (
<option key={idx}>{hue}</option>
))}
</select>
</form>
And here is a link to the code sandbox
https://codesandbox.io/s/brave-austin-ujv5xw?file=/src/App.js:1414-1673
The useeffect is giving the right value but it's only updating on the next render.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在使用React 18,在此版本中,React将批量更改,这意味着React将将您的多个固定状态应用在一起,因此您必须在使用效果中使用setColor并将其从处理中删除,类似的事情:
You are using react 18 and in this version react will batch the changes, which means that react will apply your multiple setState together so you have to use setColor in a useEffect and remove that from handleChanges, something like this:
handlehuechange
您正在更新huecolor
,在下一行中,您认为可以立即使用该新状态,因此您写了setColor(RandomColor(RandomColor)光度:lum}));
,但是huecolor
您在这里传递的仍然是旧的,因为您正在从Clousure读取它,这意味着只有在rerender之后您才能访问该新状态。解决方案是仅用setColor替换该行(RandomColor({hue:newhue,Luminosity:Lum}));
- 您可以在这里看到,我正在使用newhue
而不是HueColor
为了更新颜色。Inside
handleHueChange
you are updatinghueColor
and in next line you were thinking that you can use that new state immediately so you wrotesetColor(randomColor({ hue: hueColor, luminosity: lum }));
, buthueColor
you passed here is still old one because you are reading it from clousure, meaning only after rerender you will be able to access that new state. Solution is to just replace that line withsetColor(randomColor({ hue: newHue, luminosity: lum }));
- as you can see here I am usingnewHue
instead ofhueColor
in order to update colors.