【问题标题】:Periodic Error getting while rendering in in REACTJS在 REACTJS 中渲染时出现周期性错误
【发布时间】:2020-08-19 06:59:46
【问题描述】:

出现“无法读取未定义的属性‘值’”错误,有时代码呈现良好且输出按预期显示。可以推断,“值”在渲染之前未加载到属性“填充”。我如何更正它以仅在将值加载到组件中时才呈现

import React, { useMemo, useState, useEffect, useCallback } from "react";
import { geoPath, geoMercator, geoIdentity } from "d3-geo";
import * as d3 from "d3";
const Map = ({ stateGeographies, geoData, statecode, plotdata }) => {
  const [circledata, setCircleData] = useState([]);
  const width = 750;
  const height = 450;
  const projection = geoMercator().fitSize([width, height], {
    type: "FeatureCollection",
    features: stateGeographies
  });
  const path = useMemo(() => {
    if (!geoData) return null;
    return geoPath(geoIdentity());
  }, [geoData]);

  useEffect(() => {
    const features = () => {
      return stateGeographies.map((feature) => {
        const district = feature.properties.district;
        const state = feature.properties.st_nm;
        const obj = Object.assign({}, feature);
        const val = plotdata.filter((p) => {
          const datavalue = p.place === district ? p.value : null;
          return datavalue;
        });
        obj.id = `${statecode}-${state}${district ? "-" + district : ""}`;
        obj.value = val;
        return obj;
      });
    };
    setCircleData(features);
  }, [statecode, stateGeographies, plotdata]);
  var color = d3
    .scaleThreshold()
    .domain([2000, 5000, 8000, 10000, 15000])
    .range(["#FFA07A", "#FA8072", "#CD5C5C", "#DC143C", "#FF0000"]);

  return (
    <svg width={1000} height={600} viewBox="0 0 800 450">
      <g className="states">
        {circledata.map((d, i) => (
          <path
            key={`path-${i}`}
            d={geoPath().projection(projection)(d)}
            className="state"
            fill={color(!d.value ? 0 : d.value[0].value)}
            /*fill={function (d) {
            return color([d.value[0].value]);
          }}*/
          />
        ))}
      </g>
    </svg>
  );
};

export default Map;

【问题讨论】:

    标签: javascript reactjs d3.js rendering typeerror


    【解决方案1】:

    确保d 已定义且值有长度

    fill={color(d && d.value && d.value.length ? d.value[0].value : 0)}
    

    如果您发现错误“无法读取未定义的属性 [something]”,则您尝试在未定义的变量中调用某些内容。

    【讨论】:

    • 使用可选链:fill={d?.value?.[0]?.value || 0}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-18
    • 2021-11-15
    • 1970-01-01
    • 2019-08-17
    相关资源
    最近更新 更多