Issue
React components only re-render when state and/or props update. Since ContainerComponent
has no state and the graphData
prop doesn't change then ContainerComponent
never rerenders, nor do its children.
Solution
Add state to ContainerComponent
. When the filtedData
state is updated then ContainerComponent
will rerender, along with the children.
function ContainerComponent(props) {
const { graphData } = props;
const [filteredData, setFilteredData] = React.useState([...graphData]);
function handleClick() {
setFilteredData((data) => data.filter((x) => x > 0));
}
return (
<>
<button onClick={handleClick}>Filter</button>
<GraphComponent data={graphData} />
<TableComponent data={filteredData} />
</>
);
}
Answer for your edited question
let childData = 0;
function ContainerComponent() {
function handleClick() {
childData++;
}
return (<>
<button onClick={handleClick}>Increment</button>
<ChildComponent data={childData} />
</>);
}
childData
won't work either since now the object reference never changes, you just mutate the same reference each time. You would need to store childData
in component state, and update it to get the component to rerender.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…