简体   繁体   English

在父组件内使用组件的多个实例

[英]Using multiple instances of a component inside parent component

I have a page where multiple spinners needs to be shown.我有一个页面需要显示多个微调器。 The spinners should be hidden whenever data arrives.每当数据到达时,都应该隐藏微调器。

. . In the example I have child components where in I have mocked the data using a settimeout as if it were coming from the back-end.在示例中,我有子组件,其中我使用 settimeout 模拟了数据,就好像它来自后端一样。

I have extracted the loader as a separate component, so that it behaves as a common loader for all the items.我已将加载器提取为一个单独的组件,以便它充当所有项目的通用加载器。

Usually the API would give me array of items if present, and if not an empty array.通常 API 会给我项目数组(如果存在),如果不是空数组。

Have tried some approach but For all the cards, it's showing not found and then gets replaced with the content尝试了一些方法,但对于所有卡片,它显示未找到,然后被内容替换

Sandbox: https://codesandbox.io/embed/react-table-row-table-vdnfh?codemirror=1沙盒: https://codesandbox.io/embed/react-table-row-table-vdnfh?codemirror=1

import * as React from "react";
import { render } from "react-dom";
import "./styles.css";
import Card from "./Card";

class App extends React.Component<IProps, IState> {
  constructor(props: any) {
    super(props);
    this.state = {
      cardData1: undefined,
      cardData2: undefined,
      cardData3: undefined,
      cardData4: undefined
    };
  }

  componentDidMount() {
    this.getGraphData();
  }

  getGraphData = () => {
    this.setGraphData("graph1");
    this.setGraphData("graph2");
    this.setGraphData("graph3");
    this.setGraphData("graph4");
  };

  setGraphData = (cardNumber: string) => {
    //based on the attribute I set the corresponding card data
    if (cardNumber === "graph1") {
      setTimeout(() => {
        this.setState({ cardData1: [1, 2, 3] });
      }, 1000);
    }
    if (cardNumber === "graph2") {
      setTimeout(() => {
        this.setState({ cardData2: [3, 4, 5] });
      }, 2000);
    }

    if (cardNumber === "graph3") {
      setTimeout(() => {
        this.setState({ cardData3: [6, 7, 8] });
      }, 3000);
    }
    if (cardNumber === "graph4") {
      setTimeout(() => {
        this.setState({ cardData4: [] });
      }, 4000);
    }
  };

  render() {
    let { cardData1, cardData2, cardData3, cardData4 } = this.state;
    return (
      <>
        <Card
          name="Card1"
          data={this.state.cardData1}
          spinnerFlag={cardData1 === undefined}
        />
        <Card
          name="Card3"
          data={this.state.cardData2}
          spinnerFlag={cardData2 === undefined}
        />
        <Card
          name="Card3"
          data={this.state.cardData3}
          spinnerFlag={cardData3 === undefined}
        />
        <Card
          name="Card4"
          data={this.state.cardData4}
          spinnerFlag={cardData4 === undefined}
        />
      </>
    );
  }
}

Ah okay now I understand.啊,好吧,现在我明白了。 So your issue is that in your card component you are rendering both the data section (that either shows the data or not found) and the spinner at the same time.所以您的问题是,在您的卡片组件中,您同时呈现数据部分(显示数据或未找到)和微调器。 You need to check if the data is still being fetched (spinnerFlag) and conditionally render the spinner or the data based on that flag.您需要检查是否仍在获取数据 (spinnerFlag) 并根据该标志有条件地渲染微调器或数据。

        <div className="box">
          {
            this.props.spinnerFlag ? (
              <Spinner spinnerFlag={this.props.spinnerFlag} />
            ) : (
              <div>
                {data && data.length ? (
                  data.map((val: any, index: any) => (
                    <span key={index}>Value : {val} </span>
                  ))
                ) : (
                  <div>Not found</div>
                )}
              </div>
            )
          }
        </div>

Edit: I meant when you initialize variable just use null because youre actually setting the 'value'编辑:我的意思是当你初始化变量时只使用null因为你实际上是在设置“值”

this.state = {
  cardData1: null,
  cardData2: null,
  cardData3: null,
  cardData4: null
};

And then when you do然后当你这样做时

<Card
  name="Card1"
  data={this.state.cardData1}
  spinnerFlag={!cardData1}
/>

The ! ! is an operator which basically means 'not' and will evaluate to a boolean that is the opposite of the actual variable.是一个运算符,基本上表示“不”,并将评估为与实际变量相反的 boolean。 So if cardData1 is null (falsey), !cardData1 will be true .因此,如果cardData1null (假), !cardData1将为true Then when data is set, it will be false.那么当设置数据时,它将是错误的。

PS Fun trick, !! PS有趣的把戏, !! forces things to a boolean if you need a boolean for whatever reason如果您出于任何原因需要 boolean,则强制使用 boolean

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

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