2017-01-05 4 views
0

나는 내 상태로 데이터를 가져 와서 config 변수에서 데이터의 일부를 사용하려고하므로이 데이터를 highChart에 렌더링 할 수 있습니다. 그러나, "내 'json 호출에서 다른 데이터에 대한 정의되지 않은'SeriesDates '등의 속성을 읽을 수 없다는 오류가 계속 발생합니다. 그러나 콘솔에 상태를 기록하면 데이터가 명확하게 상태에 있습니다. config 변수에서 사용할 수 없으며 어떻게 변수 값으로 가져올 수 있습니까? 내 redux 상태 ({this.props.stock.Name})에서 데이터를 사용할 수 있지만 동일하지 않습니다. 내 JSON 호출의 출력.변수 내에서 상기 데이터를 사용하려고 할 때 구성 요소 내에서 json 데이터를 사용할 수 없습니다.

import React, { Component } from 'react'; 
import { connect } from 'react-redux'; 
import ReactHighcharts from 'react-highcharts'; 

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

    this.state = {chart: []}; 
    } 

    componentDidMount() { 
    this.ChartData(); 
    } 

    ChartData() { 
    return $.getJSON(`http://dev.markitondemand.com/MODApis/Api/Timeseries/json?symbol=${this.props.stock.Symbol}`) 
     .then((data) => { 
     var raw = JSON.stringify(data); 
     var json = JSON.parse(raw); 
     this.setState({ chart: json }); 
     console.log(this.state); 
     }); 
    } 

    render() { 

    const config = { 
     title: { 
      text: `${this.props.stock.Name}`, 
      x: -20 //center 
     }, 
     subtitle: { 
      text: `${this.props.stock.Symbol}`, 
      x: -20 
     }, 
     xAxis: { 
      categories: `${this.state.chart.Data.SeriesDates}` 
     }, 
     yAxis: { 
      title: { 
       text: 'Price' 
      }, 
      plotLines: [{ 
       value: 0, 
       width: 1, 
       color: '#808080' 
      }] 
     }, 
     tooltip: { 
      valueSuffix: '$' 
     }, 
     series: [{ 

      name: 'AAPL', 
      data: `${this.state.chart.Data.close.values}` 
     }] 
    }; 

    if (!this.props.stock) { 
     return <div></div> 
    } 

    return (
     <div> 
     <ReactHighcharts config={config}></ReactHighcharts> 
     </div> 
    ); 
    } 
} 

function mapStateToProps(state) { 
    return { 
    stock: state.selectedStock 
    }; 
} 
+0

이미 Redux를 사용하고 있으므로 차트 데이터를 전체 Redux 상태로 옮길 것이므로 구성 요소는 데이터를 가져 오는 방법과 관련이 없습니다. –

답변

0

당신은 그래서. lifecycle componentDidMount 처음 렌더링 후 트리거 반응 구성 요소에 따르면. 구성 요소가 마운트 된 후 상태를 설정하는 코드로 자세히 살펴 경우 렌더링 시간은 빈 차트 상태가됩니다. 즉 this.state.chart.Data = undefined입니다. 그래서 코드 this.state.chart.Data.SeriesDates 위의 오류가 발생합니다.

참고 : 서버에서 데이터를 가져 오는 데 시간이 걸리기 때문에 논리를 componentWillMount에 넣더라도 서버에서 데이터를 가져 오는 것이므로 동일한 오류가 발생합니다.

문제를 해결하는 방법은 두 가지가있을 수 있습니다 :

  1. 가 반환되는 데이터의 형식을 참조 몇 가지 기본 값으로 초기 상태를 설정하려면를

    this.state = {chart: { Data: { SeriesData: {}, close: {}, ... } } };

또는 2. render 메소드에서 undefined를 확인하십시오.

const Data = this.state.chart.Data; 
    if(Data){ 
    const config = { 
     title: { 
      text: `${this.props.stock.Name}`, 
      x: -20 //center 
     }, 
     subtitle: { 
      text: `${this.props.stock.Symbol}`, 
      x: -20 
     }, 
     xAxis: { 
      categories: `${this.state.chart.Data.SeriesDates}` 
     }, 
     yAxis: { 
      title: { 
       text: 'Price' 
      }, 
      plotLines: [{ 
       value: 0, 
       width: 1, 
       color: '#808080' 
      }] 
     }, 
     tooltip: { 
      valueSuffix: '$' 
     }, 
     series: [{ 

      name: 'AAPL', 
      data: `${this.state.chart.Data.close.values}` 
     }] 
    }; 
    } 

행운을 빈다.

+0

당신의 답이 맞지만 분명히 알 수 있듯이, 반응주기에서'render' 전에 함수를 가져 오는 대신 비동기 적으로 데이터를 가져 오기 때문에 어플리케이션이 실패 할 것입니다. 이 경우 라이프 사이클은 실제로 관련성이 없습니다. –

+0

일반적으로 데이터 가져 오기는 렌더링 전에 트리거되기 때문에 componentWillMount에서 수행됩니다. 예,이 경우 관련성이 없어 보입니다. 그래서 우리는 2 가지 해결책 중 하나를 거쳐야 할 것입니다. – duwalanise

+0

예 아니요. 'configWillMount'로 옮기는 것은 중요하지 않습니다. 왜냐하면 데이터 가져 오기가 비동기 적이기 때문에'this.setState'에 대한 호출은 첫 번째 렌더링 이후에 호출 될 가능성이 높습니다. 네, 당신의 솔루션은 그것을 해결할 수있는 유일한 방법 일 것입니다. –

관련 문제