在React中使用d3中的d3.json出现了解析json错误,Uncaught (in promise)如何处理

新手上路,请多包涵
import React from 'react';
import * as d3 from "d3";


class Map extends React.Component {
   constructor(props){
       super(props);
       this.Map=React.createRef();
   }

   componentDidMount(){
     this.draw();
   }

   handleChangeMap=(provinceName)=>{
       this.props.handleChangeMap(provinceName);
   }

   draw=()=>{
    let svg1=this.Map.current;
    let svg = d3.select(svg1);
    const width = +svg.attr('width');
    const height = +svg.attr('height');
    const margin = {top: 200, right: 200, bottom: 100, left: 200};
    const innerWidth = width - margin.left - margin.right;
    const innerHeight = height - margin.top - margin.bottom;
    const g = svg.append('g').attr('id', 'maingroup')
    .attr('transform', `translate(${margin.left}, ${margin.top})`);
    const projection = d3.geoMercator()
    .scale(200)
    .translate([innerWidth/2,innerHeight/2]);
    const pathGenerator = d3.geoPath().projection(projection);
    d3.json('./china.json').then(
        function(data){
            console.log(data);
            // this code is really important if you want to fit your geoPaths (map) in your SVG element; 
           
        }
    );
   }

   render(){
       return(
        <svg width="1600" height="800" id="mainsvg" ref={this.Map}></svg>
       )
   }
}

export default Map;

代码如上图,代码排查后发现是使用d3.json函数出错,出错内容为Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0。
查了很久官网了,望各位大佬指点我一下

阅读 3.1k
1 个回答

请求的返回值不是 JSON,所以解析失败了。看出错的 Unexpected token < in JSON 就大胆猜测,后端返回的是 HTML,因为 HTML 中 < 最先出现,而它不是合法 JSON 该出现的第一个字符。
新手常见的可能应该是路径有问题(返回了 HTML 或 404 页面之类的),或者没有授权自动跳转到首页 HTML 了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题