通过其同级触发状态更改时,子组件不会重新呈现

时间:2019-11-03 16:01:34

标签: reactjs react-hooks

有两个子组件(L1和L2)。两者都渲染文本和一个按钮。当按下L1中的按钮时,它将更改L1的文本(在下面的代码中可以正常工作)。当按下L2中的按钮时,它将更改L2的文本(在下面的代码中也可以正常工作)。

L1组件还具有第二个按钮,尽管它也可以更改位于另一个组件L2内部的文本。这是我的代码不再起作用的地方。仍会调用使用的相同函数,并更改状态值,但L2组件将永远不会重新渲染/其文本保持不变。

父母:

export const Parent = ({ hours, day, location, context }) => {

const numItemsToShow:number = 12;
const [showMore, setShowMore] = useState<any>({
    showMoreX: false,
    showMoreY: false,
    showMoreAmountX: 50 * numItemsToShow,
    showMoreAmountY: 50 * numItemsToShow,
    showMoreAmountTotalX: 0 //x cannot be set to auto => need to know total width
});


const doShowMoreX = (e) => {
    console.log('1')
    setShowMore((prevState) => {
        return {...prevState, showMoreX: !showMore.showMoreX};
    });
}

const doShowMoreY = (e) => {
    console.log('2')
    setShowMore((prevState) => { //PROBLEM: When called by L1, the Text in L2 never changes even though state changes - when called by L2 its all fine/text changes
        return {...prevState, showMoreY: !showMore.showMoreY};
    });
}


return (
    <>
    <ErrorBoundary>
        {
            (context === 'detailed') ?
            <L2 day={day} hours={hours} location={location} state={showMore} doShowMoreY={doShowMoreY}></L2> :
            <L1 day={day} hours={hours} location={location} state={showMore} doShowMoreX={doShowMoreX} doShowMoreY={doShowMoreY}></L1>
        }
    </ErrorBoundary>
</>
)
}

L1(儿童1)

export const L1 = ({ day, hours, location, state, doShowMoreX, doShowMoreY }) => {
const {showMoreX, showMoreAmountX, showMoreAmountTotalX} = state;

return (
    <div>
        {
            <div>
                <div>{(showMoreX) ? 'Some Output L1' : '-'}</div>
                <button onClick={doShowMoreX}>Change Output L1</button><br/>
                <button onClick={doShowMoreY}>Change Output L2</button> <!-- PROBLEM: L2 Text never changes even though doShowMoreY-function is called and state value is changed -->
            </div>
        }

    </div>
)
}

L2(儿童2)

export const L2 = ({ day, hours, location, state, doShowMoreY }) => {
const { showMoreY, showMoreAmountY } = state;
return (
    <div>
        {
            <div>
                <div>{(showMoreY) ? 'Some Output L2' : '-'}</div>
                <button onClick={doShowMoreY}>Change Output L2</button>
            </div>
        }

    </div>
)
}

1 个答案:

答案 0 :(得分:0)

我的子组件无法通过公共父组件更新其兄弟组件的原因是公共父组件的渲染方法中的条件语句。

return (
    <>
        <ErrorBoundary>
            {
            (context === 'detailed') ? //context value was the same and thus child never rerendered
            <L2 day={day} hours={hours} location={location} state={showMore} doShowMoreY={doShowMoreY}></L2> :
            <L1 day={day} hours={hours} location={location} state={showMore} doShowMoreX={doShowMoreX} doShowMoreY={doShowMoreY}></L1>
            }
        </ErrorBoundary>
    </>
)

尽管如此,我仍然需要该条件语句,因此我最终使用redux在子内部直接检查了更新的值(同样可以在react context API中使用)。