gpt4 book ai didi

reactjs - 可以更改外部组件中的对象(元素)吗?

转载 作者:行者123 更新时间:2023-12-01 23:08:36 26 4
gpt4 key购买 nike

当我在另一个组件上调用 changeArea 方法时,我想要更改区域(元素)。

我想这样做。

首先,App.js

export default function App(props) {
const [area, setArea] = React.useState(<><Button/><Button/></>)

const changeArea = (element) => {
setArea(element);
}

return (
<div>
{<area/>}
<ChildApp changeArea={changeArea}/>
</div>
);
}

还有,ChildApp.js

export default function ChildApp(props) {

// I want do call to change the area.
props.changeArea(<></Select></>);

}

无论如何,这段代码不起作用。

错误

Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

PS. It’s a simplification of the way I want to do it.

最佳答案

既然您调用props.changeArea(<></Select></>);在组件的主体中,因此每次组件渲染(函数调用)时,您都会设置以下状态父级( App ),组件中的每个更新状态都会导致重新渲染(调用)组件及其子组件,因此您处理循环,您 props.changeArea(<></Select></>); ,它会导致重新渲染它的父级,并重新渲染父级导致调用 props.changeArea(<></Select></>);您不能直接调用函数体,您可以在useEffect中进行调用或在某些eventHandler 。像这样:

export default function ChildApp(props) {
...
useEffect(()=> {
props.changeArea(<></Select></>);
}, []);
...
}

在上面的代码中,props.changeArea(<></Select></>);第一次来电ChildApp渲染以及 ChildApp 的其他渲染它从不调用 props.changeArea .

如果您想了解如何在 eventHandler 中做到这一点你可以看看@Akhil 解决方案。

关于reactjs - 可以更改外部组件中的对象(元素)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70343647/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com