React钩子:如何使用useState()更新嵌套对象上的状态? [英] React hooks: How do I update state on a nested object with useState()?

查看:86
本文介绍了React钩子:如何使用useState()更新嵌套对象上的状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件可以接收如下所示的道具:

  const样式= {字体:{尺寸: {值:"22",单位:"px"},重量:粗体",颜色:#663300",家庭:"arial",居中对齐'}}; 

我正在尝试更新 align 属性,但是当我尝试更新对象时,我最终只用 align 属性替换了整个对象./p>

这是我的更新方式:

  const {... styling} =样式;const [style,setStyle] = useState(styling);返回 (< RadioButtonGrouponChange = {(event)=>{setStyle({... style,font:{align:event.target.value}});console.log(style);}}/>); 

当我console.log style 时,我只得到了 {"font":{"align":"left"}} .我希望看到整个对象具有 align 的更新值.我是解构的新手,所以我在这里做错了什么?

解决方案

您还需要使用传播语法来复制字体对象属性.另外,在尝试根据先前状态更新当前状态时,请使用回调模式

 < RadioButtonGrouponChange = {(event)=>{setStyle(prevStyle =>({... prevStyle,字体:{... prevStyle.font,对齐:event.target.value}}));console.log(style);}}/> 

I have a component that receives a prop that looks like this:

const styles = {
    font: {
        size: {
            value: '22',
            unit: 'px'
        },
        weight: 'bold',
        color: '#663300',
        family: 'arial',
        align: 'center'
    }
};

I'm trying to update the align property, but when I try to update the object, I wind up replacing the whole object with just the align property.

this is how I'm updating it:

const { ...styling } = styles;
const [style, setStyle] = useState(styling);

return (
        <RadioButtonGroup
            onChange={(event) => {
                setStyle({ ...style, font: { align: event.target.value } });
                console.log(style);
            }}
        />);

When I console.log style I just get {"font":{"align":"left"}} back. I expected to see the whole object with the updated value for align. I'm new to destructuring so what am I doing wrong here?

解决方案

You need to use spread syntax to copy the font object properties too. Also while trying to update current state based on previous, use the callback pattern

<RadioButtonGroup
  onChange={(event) => { 
    setStyle(prevStyle => ({
        ...prevStyle,
        font: { ...prevStyle.font, align: event.target.value }
    }));
    console.log(style);
  }}
/>

这篇关于React钩子:如何使用useState()更新嵌套对象上的状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆