cod*_*mon 5 javascript reactjs
我有一个创建三个单选按钮的组件。选择一个应该更新我在其他地方的上下文存储。
我的状态看起来像这样:
const styles = {
font: {
size: {
value: '22',
unit: 'px'
},
weight: 'bold',
color: '#663300',
family: 'arial',
align: 'center'
}
};
Run Code Online (Sandbox Code Playgroud)
我这样存储我的状态:
const myContext = useEmailContext();
const { ...styling } = styles;
const [style, setStyle] = useState({ styling });
Run Code Online (Sandbox Code Playgroud)
然后我的组件触发函数onChange:
return (
<RadioButtonGroup
onChange={(event) => {
setIsChecked({ checked: event.target.value });
setStyle({ ...styling, font: { ...styling.font, align: event.target.value } });
console.log(style);
myContext.setStyles(style);
}}
/>
Run Code Online (Sandbox Code Playgroud)
当我单击按钮时,该函数会触发,但 console.log 显示之前的状态,而不是新更新的状态。同样,我的上下文也落后一步更新。
这里发生了什么?
状态更新与 useState hooks updater 异步。您可以在这篇文章中阅读更多相关信息:
但是,您可以像这样解决上下文值更新问题
return (
<RadioButtonGroup
onChange={(event) => {
setIsChecked({ checked: event.target.value });
const newStyle = { ...styling, font: { ...styling.font, align: event.target.value } }
setStyle(newStyle);
myContext.setStyles(newStyle);
}}
/>
)
Run Code Online (Sandbox Code Playgroud)
或者您可以使用 useEffect hook 更新上下文值,例如
useEffect(() => {
myContext.setStyles(styling);
}, [styling]);
return (
<RadioButtonGroup
onChange={(event) => {
setIsChecked({ checked: event.target.value });
setStyle({ ...styling, font: { ...styling.font, align: event.target.value } });
}}
/>
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
768 次 |
| 最近记录: |