简体   繁体   English

子组件不会重新渲染

[英]Child component does not re-render

I'm working with two functional react components where I'm passing an id (the state) of a clicked item down to a child component via a prop.我正在使用两个功能性反应组件,其中我通过道具将单击项目的id (状态)传递给子组件。

Problem问题

The id does render in the child component, but when the state is updated in the parent the child component creates a new render instead of updating the previous render. id 确实在子组件中渲染,但是当父组件中的状态更新时,子组件会创建一个新的渲染而不是更新之前的渲染。 So eg.所以例如。 the child component displays the id 1 and when another item is clicked the child component displays both 1 and new id子组件显示id 1 ,当单击另一个项目时,子组件显示1和新id

Parent class:父类:

import ReactDOM from "react-dom";
import React from "react";
import TreeView from "@material-ui/lab/TreeView";
import ExpandMoreIcon from "@material-ui/icons/ExpandMore";
import ChevronRightIcon from "@material-ui/icons/ChevronRight";
import TreeItem from "@material-ui/lab/TreeItem";
import Test from "./test";
const { useState, useCallback } = React;

export default function MyTreeItem(props) {
  const [childNodes, setChildNodes] = useState(null);
  const [expanded, setExpanded] = React.useState([]);
  const [activeItemId, setActiveItemId] = useState();

  function fetchChildNodes(id) {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve({
          children: [
            {
              id: "2",
              name: "Calendar"
            },
            {
              id: "3",
              name: "Settings"
            },
            {
              id: "4",
              name: "Music"
            }
          ]
        });
      }, 1000);
    });
  }

  const handleChange = (event, nodes) => {
    const expandingNodes = nodes.filter(x => !expanded.includes(x));
    setExpanded(nodes);
    if (expandingNodes[0]) {
      const childId = expandingNodes[0];
      fetchChildNodes(childId).then(result =>
        setChildNodes(
          result.children.map(node => <MyTreeItem key={node.id} {...node} />)
        )
      );
    }
  };

  const renderLabel = item => (
    <span
      onClick={event => {
        console.log(item.id);
        setActiveItemId(item.id);
        // if you want after click do expand/collapse comment this two line
        event.stopPropagation();
        event.preventDefault();
      }}
    >
      {item.name}
    </span>
  );

  return (
    <div>
      <TreeView
        defaultCollapseIcon={<ExpandMoreIcon />}
        defaultExpandIcon={<ChevronRightIcon />}
        expanded={expanded}
        onNodeToggle={handleChange}
      >
        {/*The node below should act as the root node for now */}
        <TreeItem nodeId={props.id} label={renderLabel(props)}>
          {childNodes || [<div key="stub" />]}
        </TreeItem>
      </TreeView>
      <Test test={activeItemId} />
    </div>
  );
}
const rootElement = document.getElementById("root");
ReactDOM.render(<MyTreeItem id="1" name="Applications" />, rootElement);


Child class:儿童班:

import React, { useState, useEffect } from "react";

export default function Test({ test }) {
  return <h1>{test}</h1>;
}

To reproduce the problem: https://codesandbox.io/s/material-demo-5kfbl重现问题: https : //codesandbox.io/s/material-demo-5kfbl

Problem comes from [unexpected] recurrency - setChildNodes renders 'tree root' components <MyTreeItem /> as childs, each of them with own states, handlers etc.问题来自 [意外] 重复 - setChildNodes将“树根”组件<MyTreeItem />渲染为子组件,每个组件都有自己的状态、处理程序等。

You can fix this by render <TreeItem /> as childs:您可以通过将<TreeItem />渲染为孩子来解决此问题:

    setChildNodes(
      result.children.map(node => <TreeItem nodeId={node.id} label={renderLabel(node)} /> )
    )

Working example: https://codesandbox.io/s/material-demo-k8mq1工作示例: https : //codesandbox.io/s/material-demo-k8mq1

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

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