Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

javascript - Functional Component child component does not re-rendered after its props is updated by its Parent

In the code below:

ParentComponent.js

let childData = 0;

function ParentComponent() {
    function handleClick() {
        childData++;
    }

    return (<>
        <button onClick={handleClick}>Increment</button>
        <ChildComponent data={childData} />
    </>);
    }

ChildComponent.js

export default function ChildComponent(props) {
    return(<p>Child Component: {props.data}</p>);
}

Why after clicking Increment button the child component still shows the old value and does not re-render?

question from:https://stackoverflow.com/questions/65648469/functional-component-child-component-does-not-re-rendered-after-its-props-is-upd

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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} />
    </>
  );
}

Edit functional-component-not-re-rendered-after-it-props-is-updated

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...