如何解决在REACTJS中渲染时出现周期性错误
得到“无法读取未定义的属性'值'”错误,有时代码呈现良好,并且输出按预期显示。可以推断出,“值”在呈现之前未加载到属性“填充”中。我如何将其校正为仅在将值加载到组件中时呈现
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;
解决方法
确保已定义d
并且值具有长度
fill={color(d && d.value && d.value.length ? d.value[0].value : 0)}
如果您发现错误“无法读取未定义的属性[something]”,则您尝试在未定义的变量中调用某些内容。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。