简体   繁体   English

使用useEffect时如何在reactJS中写if else语句?

[英]How to write if else statement in reactJS when using useEffect?

Following is the code I'm using to return the Plotly graph, What I need to do in here is I need to return a message or different layout when the graph data is empty or there is nothing to show on the graph.以下是我用来返回 Plotly 图形的代码,我需要在这里做的是当图形数据为空或图形上没有任何内容时,我需要返回一条消息或不同的布局。 use a default content like no data available if no data for charts.如果图表没有数据,则使用默认内容,例如没有可用数据。 How do I do that?我怎么做?

 import React, { useEffect } from "react"; import Plot from "react-plotly.js"; import PropTypes from "prop-types"; let dataArray; let index; let obj; function PlotlyStackedChart({ labels, data, xTitle, yTitle, mainTitle, preHeading }) { useEffect(() => { dataArray = []; for (index = 0; index < data.length; index += 1) { obj = { x: labels, y: data[index].data, type: "bar", name: data[index].name, }; dataArray.push(obj); } }, [data]); return ( <> <Plot data={dataArray} layout={{ barmode: "stack", autosize: true, title: { text: preHeading + mainTitle, y: 0.9, }, margin: { t: 225, }, xaxis: { // all "layout.xaxis" attributes: #layout-xaxis title: { text: xTitle, font: { family: "Arial Black", }, }, // more about "layout.xaxis.title": #layout-xaxis-title // dtick: 1, }, yaxis: { // all "layout.yaxis" attributes: #layout-yaxis title: { text: yTitle, font: { family: "Arial Black", }, }, // more about "layout.yaxis.title": #layout-yaxis-title }, font: { // family: "Courier New, monospace", size: 12, color: "#7f7f7f", }, legend: { bgcolor: "transparent", x: 0, y: 1.4, xanchor: "auto", traceorder: "normal", orientation: "h", }, marker: { size: 40 }, }} useResizeHandler style={{ width: "100%", height: 600 }} /> </> ); } export default PlotlyStackedChart; PlotlyStackedChart.defaultProps = { xTitle: "", yTitle: "", mainTitle: "", preHeading: "", }; // Typechecking props for the MDDatePicker PlotlyStackedChart.propTypes = { labels: PropTypes.oneOfType([PropTypes.string, PropTypes.array]).isRequired, xTitle: PropTypes.string, yTitle: PropTypes.string, mainTitle: PropTypes.string, preHeading: PropTypes.string, data: PropTypes.oneOfType([PropTypes.string, PropTypes.array, PropTypes.object]).isRequired, };

explaining further, If there is no data to plot in the graph I want to return the following code else the current one which retrieves the data and plot in the graph.进一步解释,如果图中没有 plot 的数据,我想返回以下代码,否则返回当前检索数据的代码和图中的 plot。

 return { "layout": { "xaxis": { "visible": false }, "yaxis": { "visible": false }, "annotations": [ { "text": "No matching data found", "xref": "paper", "yref": "paper", "showarrow": false, "font": { "size": 28 } } ] } }

You can try returning the empty content template if there is no content.如果没有内容,您可以尝试返回空的内容模板。

import React, { useEffect } from "react";
import Plot from "react-plotly.js";
import PropTypes from "prop-types";

let dataArray;
let index;
let obj;
function PlotlyStackedChart({ labels, data, xTitle, yTitle, mainTitle, preHeading }) {
  useEffect(() => {
   if(data?.length){ // <--- place condition here
     dataArray = [];
     for (index = 0; index < data.length; index += 1) {
       obj = {
         x: labels,
         y: data[index].data,
         type: "bar",
         name: data[index].name,
       };
       dataArray.push(obj);
     }
   }
  }, [data]);

  // Place this conditional return
  if(!data?.length) {
    return <>No data found</>
  }

  return (
    <>
      <Plot
        data={dataArray}
        layout={{
          barmode: "stack",
          autosize: true,
          title: {
            text: preHeading + mainTitle,
            y: 0.9,
          },
          margin: {
            t: 225,
          },
          xaxis: {
            // all "layout.xaxis" attributes: #layout-xaxis
            title: {
              text: xTitle,
              font: {
                family: "Arial Black",
              },
            }, // more about "layout.xaxis.title": #layout-xaxis-title
            // dtick: 1,
          },
          yaxis: {
            // all "layout.yaxis" attributes: #layout-yaxis
            title: {
              text: yTitle,
              font: {
                family: "Arial Black",
              },
            }, // more about "layout.yaxis.title": #layout-yaxis-title
          },
          font: {
            // family: "Courier New, monospace",
            size: 12,
            color: "#7f7f7f",
          },
          legend: {
            bgcolor: "transparent",
            x: 0,
            y: 1.4,
            xanchor: "auto",
            traceorder: "normal",
            orientation: "h",
          },
          marker: { size: 40 },
        }}
        useResizeHandler
        style={{ width: "100%", height: 600 }}
      />
    </>
  );
}

export default PlotlyStackedChart;

useEffect is entirely irrelevant to the problem you describe. useEffect与您描述的问题完全无关。

If you want to render something different when the array is empty, then do it in the render logic, not as an effect.如果您想在数组为空时呈现不同的内容,请在呈现逻辑中执行,而不是作为效果。

if (data.length === 0) {
    return <Loading />
} else {
   return <Plot .../>
}

That said, your effect logic is broken.也就是说,你的效果逻辑被打破了。 You can't just assign a new array to a variable and have React render it.你不能只是将一个新数组分配给一个变量并让 React 渲染它。 You've done nothing to tell React that it needs to do a re-render.你没有告诉 React 它需要重新渲染。 Make data a state variable (with useState ).使data成为 state 变量(使用useState )。

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

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