React hooks: How do I update state on a nested object with useState()?

前端 未结 6 824
一个人的身影
一个人的身影 2021-02-08 13:43

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

const styles = {
    font: {
        size: {
            value: \'22\',
            unit: \'px\'
           


        
6条回答
  •  青春惊慌失措
    2021-02-08 13:53

    First: const { ...styling } = styles; is the same as: const styling = styles;

    But you may skip that altogether, just use [...] = useState(styles)

    setStyle() accepts a function which receives the current state, in your case style. So you may use the spread operator ... to create new object and add values to it.

    setStyle(style => ({ ...style, font: { ...style.font, align: event.target.value } ) ) );

    Above code uses Arrow function, this could also be written as a normal function, but probably easier to understand:

    setStyle( function (style) {
        return  {
            ...style,
            font: {
                ...style.font,
                align: 'center'
            }
        }
    });
    

    Your console.log in setStyle displays current style, as changed style will be seen on next render. So I've moved the console.log before return.

    const [style, setStyle] = useState(styles);
    
    console.log(style);
    
    return (
             {
                    setStyle(style => ({ ...style, font: { ...style.font, align: event.target.value } ) ) );
                }}
            />);
    

    Here are some links to help you understand all that:

    • Spread operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
    • useState hook: https://reactjs.org/docs/hooks-state.html
    • Arrow functions: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

提交回复
热议问题