使用 MUI Paper/Styled 时,为什么子组件会在父状态更改时重新挂载?

问题描述 投票:0回答:1

当子组件包装在 MUI 样式的 Paper 组件中时,每次作为 prop 传递的父状态发生更改时,它都会重新挂载。

我在下面创建了这种意外行为的最小工作示例。如果您只是从父组件中删除

<Item>
,子组件将进行渲染而不是重新安装。我希望有人能解释为什么会出现这种行为。

import React, { useState, useEffect } from 'react';
import Paper from '@mui/material/Paper';
import { styled } from '@mui/material/styles';

const ChildComponent = ({ testValue }) => {

    useEffect(() => {
        console.log("I've been mounted");
      }, []); 

    return (
        <div>
            <p>Test Value: {testValue}</p>
        </div>
    );
};

const ParentComponent = () => {
    const [testValue, setTestValue] = useState("Initial Value");

    const Item = styled(Paper)({
      textAlign: 'center',
    }); 

    const handleChangeValue = () => {
        setTestValue("Updated Value");
    };

    return (
        <div>
            <button onClick={handleChangeValue}>Change Test Value</button>
            <Item>
            <ChildComponent testValue={testValue} />
            </Item>
        </div>
    );
};

export default ParentComponent;
reactjs material-ui
1个回答
1
投票

尝试将 Item 定义移到 ParentComponent 定义之外:

const Item = styled(Paper)({
  textAlign: 'center',
}); 

const ParentComponent = () => { ... }

当您更改 ParentComponent 内部的状态时,它会重新运行该组件内的所有代码。因此,您的“Item”组件会随着每次状态更改而重新初始化,迫使其子组件重新安装,因为它被视为一个全新的组件。

© www.soinside.com 2019 - 2024. All rights reserved.