简体   繁体   English

从其他组件 React.js 诱导重新渲染

[英]Induce re-render from other component React.js

I'd like to induce a re-render from another component, avoiding the "triggering component" to re-render.我想诱导另一个组件重新渲染,避免“触发组件”重新渲染。

const App = () => {

    const [isPopUpActive, setIsPopUpActive] = useState(false)

    const popUpOnOff = () => {
        if(isPopUpActive)
            setIsPopUpActive(false)
        else
            setIsPopUpActive(true)
    }

    return (
        <div>
            <SomeComponent
                trigger={popUpOnOff}
            />
            <PopUpComponent
                isActive={isPopUpActive}
            />
        </div>
    )
}

I thought wrapping the SomeComponent with React.memo and changing a prop in the PopUpComponent would do it, but calling the trigger function in the SomeComponent re-renders everything.我认为用React.memo SomeComponent更改PopUpComponent中的道具就可以了,但是在 SomeComponent 中调用trigger SomeComponent重新渲染所有内容。 Is there a way to avoid the first component to re-render?有没有办法避免第一个组件重新渲染?

The identity of the popUpOnOff function changes on each render, so the memoized component can't do anything. popUpOnOff function 的标识在每次渲染时都会发生变化,因此 memoized 组件不能做任何事情。

You will need to memoize that callback instead, making it depend on the data it uses:您将需要记住该回调,使其取决于它使用的数据:

const App = () => {
  const [isPopUpActive, setIsPopUpActive] = useState(false);

  const popUpOnOff = useCallback(() => {
    setIsPopUpActive(!isPopUpActive);
  }, [isPopUpActive, setIsPopUpActive]);

  return (
    <div>
      <SomeComponent trigger={popUpOnOff} />
      <PopUpComponent isActive={isPopUpActive} />
    </div>
  );
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM