【问题标题】:Not sure if callback inside d3.json get called [duplicate]不确定 d3.json 中的回调是否被调用 [重复]
【发布时间】:2019-12-12 10:22:14
【问题描述】:

我正在尝试使用 d3 选择一些元素,附加 g 并在 svg 内生成一个轴。

我已经调试了renderWeather 内部的每个步骤,似乎d3.json 确实被执行了,但我没有看到任何元素呈现。我不知道为什么。

import React, { Component } from 'react'
import * as d3 from 'd3'


 export default class Weather extends Component { 

 componentDidMount () {
    this.renderWeather()
 }

 componentDidUpdate () {
    this.renderWeather()
 }

 renderWeather = () => {

  const tmp = (d) => {
  const xScale = d3
  .scaleLinear()
  .domain([1, 10])
  .range([20, 470])

  const yScale = d3
  .scaleLinear()
  .domain([0, 40])
  .range([480, 20])

  const xAxis = d3
  .axisBottom()
  .scale(xScale)
  .tickSize(480)
  .ticks(8)

  d3.select(this.refs.container)
  .append('g')
  .attr('id', 'xAxisG')
  .call(xAxis)

  d3.select(this.refs.container)
  .append('rect')
  .style('width', 100)
  .style('height', 100)

// I haven't used any data, just trying to make it work first
}


  // dummy url here
  d3.json('https://google.com', tmp)
}

render() {
 return (
  <svg ref="container">
  </svg>
)

} }

我希望 xAxis 在底部,但在 &lt;svg&gt;&lt;/svg&gt; 内部什么也看不到,这是为什么?

【问题讨论】:

    标签: javascript reactjs d3.js


    【解决方案1】:

    D3.js D3-fetch module 使用 Fetch API 来处理 HTTP 请求。

    因此,要加载和解析 JSON 对象,您需要解析在 then() 语句中返回的承诺。

    d3.json('some-path').then(response => {
      console.log(response); 
      // handle the rest here
      tmp(response);
    });
    

    同样,renderWeather() 方法中来自tmp 的匿名函数应该在then() 语句中调用,因为图表的呈现取决于d3.json() 返回的数据。

    【讨论】:

    • 这个d3.json('https://google.com').then(d =&gt; tmp(d)) 有效
    • @jen007 啊,是的,我刚刚意识到你创建了一个匿名函数。我会相应地更新我的答案。
    • 有没有办法将 json 响应 d 公开为全局变量,或者这是访问 d 的唯一方法?
    • 您可以尝试将其分配给您班级中的一个属性!这样,您可以在课堂上的任何其他地方访问它
    • d3.json('https://google.com').then(d =&gt; this.data = d) 将有 this.data 可用于整个反应组件。谢谢!!
    猜你喜欢
    • 1970-01-01
    • 2018-08-08
    • 1970-01-01
    • 2014-10-05
    • 1970-01-01
    • 1970-01-01
    • 2016-01-30
    • 1970-01-01
    • 2012-03-06
    相关资源
    最近更新 更多