React memo 允许重新渲染到forwardRef

Muh*_*mar 3 reactjs react-functional-component

我有一个组件定义为

export default function MyComp({
    ...someprops
}) {
    const [data, setData] = useState([]);
    const searchRef = useRef();

    return (
        <Box>
            {!showEmptyState ? (
                <LzSearch
                    onUpdate={(items) => setData(items)}
                    ref={searchRef}
                />
            ) : (
               <Box />
            )}

        </Box>
    );
}
Run Code Online (Sandbox Code Playgroud)

其中 LzSearch 定义为

const LzSearch = forwardRef((props, ref) => {
    const {       
        ...rest
    } = props;
    const classes = useStyles();
    const hashData = {};

    console.log(hashData);

    function updateHashData() {
       // Function is called at some point after getting data from API
       setHashData(...);
       onUpdate(...)
    }

    return (
        <Box>
            {`Some components`}
        </Box>
    );
});

export default memo(LzSearch);
Run Code Online (Sandbox Code Playgroud)

调用 onUpdate() 后,我的主要组件已更新,但它随后重新渲染我的 LzSearch 组件并重置 hashData。我已经添加了备忘录,但它做同样的事情。

如何避免重新渲染。

Nic*_*wer 5

这与裁判无关。LzSearch正在重新渲染,因为onUpdateprop 正在改变。MyComp将需要使用useCallback来保持onUpdate渲染之间的功能相同:

export default function MyComp({
    ...someprops
}) {
    const [data, setData] = useState([]);
    const searchRef = useRef();

    const onUpdate = useCallback((items) => {
      setData(items);
    }, [])

    return (
        <Box>
            {!showEmptyState ? (
                <LzSearch
                    onUpdate={onUpdate}
                    ref={searchRef}
                />
            ) : (
               <Box />
            )}

        </Box>
    );
}
Run Code Online (Sandbox Code Playgroud)

重新渲染我的 LzSearch 组件并重置 hashData

请注意,这memo只是一种性能优化工具,而不是修复错误的方法。如果您的组件由于某种原因发生重新渲染,则需要正常工作。memo 可能会停止某些渲染,但它不能保证组件永远不会重新渲染。即使使用 useMemo 也可能导致重新渲染的示例包括:更改 props、更改状态、更改上下文、严格模式的双重渲染功能、并发模式中止然后重复组件树的一部分。