React - 如何将正确的道具从长 运行 操作传递给子组件

React - how to pass the correct prop to a child component from a long running operation

我有一个简单的反应 class...

import React, { Component } from 'react';
import './App.css';
import ProbabilityGraph from './GraphComponent/ProbabilityGraph'
import * as d3dsv from "d3-dsv";
import * as d3request from "d3-request";     
class App extends Component {
  render() {

    const url = 'http://xxx.x.x.x:xxxx/someCSV.csv';

    const dataReq = d3request.request(url).get(function(error, data){
        // console.log(data);
        const dataFinal = d3dsv.csvParse( data.responseText)
        return dataFinal    
            // console.log(dataFinal)
    });


    return (
    <div style={{textAlign:"center"}}>
        <h1> Maybe Do Something </h1>

        <ProbabilityGraph data={dataReq}/>

      </div>
    );
  }
}

export default App;

d3request 和 parse 需要一点时间。我认为正在发生的事情是,在反应初始化组件时 dataFinal 变量还没有被填满,所以什么都没有呈现。

这个问题的正确答案是什么? 'ProbabilityGraph' 将进一步处理数据,然后呈现一条线(它基于 Victory Charts)...可以很好地处理一些示例数据。

您需要在 this.setState 的帮助下设置 state 经过长时间的操作,一旦您调用此方法,它会强制组件再次呈现,但现在您的状态将有一些您可以使用 this.state.XXX 访问的值并将其传递给您的 children,

最好在 componentDidMount() 中执行这些操作,这样它就不会阻塞组件的渲染。

将您的代码更改为以下将适用于您。

import React, { Component } from 'react';
import './App.css';
import ProbabilityGraph from './GraphComponent/ProbabilityGraph'
import * as d3dsv from "d3-dsv";
import * as d3request from "d3-request";     
class App extends Component {
    constructor(){
        this.state = {
            dataReq: {}
        };
    }
    componentDidMount(){
        const url = 'http://xxx.x.x.x:xxxx/someCSV.csv';

        d3request.request(url).get(function(error, data){
            const dataFinal = d3dsv.csvParse( data.responseText)
            this.setState({dataReq: dataFinal});

        });
    }
  render() {
    return (
    <div style={{textAlign:"center"}}>
        <h1> Maybe Do Something </h1>

        { dataReq && <ProbabilityGraph data={this.state.dataReq}/> }

      </div>
    );
  }
}

export default App;

您可以添加一个 "dataReq" 状态。然后在 componentDidMount() 循环中获取您的数据,并更新您的 "dataReq" 状态。这将触发重新渲染。

import React, { Component } from 'react';
import './App.css';
import ProbabilityGraph from './GraphComponent/ProbabilityGraph'
import * as d3dsv from "d3-dsv";
import * as d3request from "d3-request";

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      dataReq = {}
    }
  }

  componentDidMount() {
    const url = 'http://xxx.x.x.x:xxxx/someCSV.csv';

    d3request.request(url).get(function(error, data){
      const dataFinal = d3dsv.csvParse( data.responseText)

      this.setState({dataReq: dataFinal})
    });
  }

  render() {
    return (
      <div style={{textAlign:"center"}}>
        <h1> Maybe Do Something </h1>
        <ProbabilityGraph data={this.state.dataReq}/>
      </div>
    );
  }
}

export default App;