React钩子中的React类组件-DOM不更新

问题描述 投票:0回答:1

我的组成如下:

const HookComponent = (props)=> {

    let [month, changeMonth] = useState(moment());


    return ( 
        <ChildComponent
            month={month}
            onChange={m => changeMonth(m)}
            minStep={5}
            prevMonthIcon="ion-ios-arrow-left"
            nextMonthIcon="ion-ios-arrow-right"
          />
    )
}

ChildComponent是一个类组件,它使用setState更新月份。上面的问题是更改没有反映在DOM上,但是父组件中的状态正在更改(通过用户输入-按钮更改了ChildComponent中的状态)。我记录了下来,并确认父母的月份在变化。在挂钩中使用类组件时,react的某些限制吗?

当我将HookComponent转换为类组件并使用setState更改月份时,它按预期方式工作,并且DOM在输入更改时发生更改。

reactjs react-hooks react-component
1个回答
0
投票

[InputMoment组件似乎没有使用month道具,而是使用了moment道具。

[而且,似乎InputMoment返回的时刻与moment属性传递的实例相同。这导致执行changeMonth语句时,由于引用未更改,因此不会重新呈现元素。

您可以通过在状态下存储对象来解决此问题。调用changeMonth时,您传递了一个新对象,然后正确重新渲染了InputMoment

const HookComponent = (props)=> {
    let [month, changeMonth] = useState({ m: moment() });

    return ( 
        <ChildComponent
            moment={month.m}
            onChange={m => changeMonth({ m })}
            minStep={5}
            prevMonthIcon="ion-ios-arrow-left"
            nextMonthIcon="ion-ios-arrow-right"
          />
    )
}
© www.soinside.com 2019 - 2024. All rights reserved.