当状态更改由其同级组件触发时,子组件不重新绘制



有两个子组件(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>
)
}

我的子组件无法通过公共父组件更新其同级组件的原因是公共父组件的呈现方法中的条件语句。

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上下文API(。

相关内容

  • 没有找到相关文章

最新更新