【问题标题】:Can change an object(element) in an external component?可以更改外部组件中的对象(元素)吗?
【发布时间】:2022-01-17 10:56:48
【问题描述】:

当我在另一个组件上调用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

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。这是对我想做的方式的简化。

【问题讨论】:

    标签: reactjs react-hooks react-functional-component


    【解决方案1】:
    const ChildApp = (props) => {
      const buttonHandler = () => {
        props.changeArea(<h1>World</h1>)
      }
      return <><button onClick={buttonHandler}>Hello</button> </>
    }
    
    export default function App() {
      const [area, setArea] = React.useState(<><h1>Hello</h1></>)
        const changeArea = (element) => {
            setArea(element);
        }
        return (
            <div>
                {area}
                <ChildApp changeArea={changeArea}/>
            </div>
        );
    }
    

    【讨论】:

    • 感谢您提出的方法,我理解了这个概念。
    【解决方案2】:

    由于您在组件的主体中调用props.changeArea(&lt;&gt;&lt;/Select&gt;&lt;/&gt;);,因此每次您的组件呈现(函数调用)时,您都会设置 父(App),组件中的每个更新状态都会导致重新渲染(调用)组件及其子组件,因此您处理循环,props.changeArea(&lt;&gt;&lt;/Select&gt;&lt;/&gt;);,它会导致重新渲染它的父组件,并且重新渲染调用props.changeArea(&lt;&gt;&lt;/Select&gt;&lt;/&gt;);的父原因你不能直接调用你的函数体,你可以在useEffect或一些eventHandler中调用。像这样:

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

    在上面的代码中,props.changeArea(&lt;&gt;&lt;/Select&gt;&lt;/&gt;); 第一次调用ChildApp 渲染,而在ChildApp 的其他渲染中它从不调用props.changeArea

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

    【讨论】:

    • 谢谢!您的解决方案是正确的源代码!
    • 不客气。
    猜你喜欢
    • 2016-10-22
    • 1970-01-01
    • 2018-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-20
    • 2022-07-19
    相关资源
    最近更新 更多