2017-03-28 6 views
1

다음과 같은 반응 구성 요소가 있습니다. 내부적으로 highcharts-react를 사용하여 API에 상태 속성 중 일부를 제공하여 API에서 데이터를 가져 와서 차트를 렌더링합니다.React 구성 요소의 AJAX 요청

export default class CandlestickChart extends React.Component { 
    constructor (props) { 
     super(props); 
     this.state = { 
      apiParam1: this.props.propData.param1, 
      apiParam2: this.props.propData.param2, 
      chartConfig: this.getChartConfig(this.props.apiParam1), 
     }; 
    } 

    componentDidMount() { 
     this.renderChart(); 
    } 

    render() { 
     return (
      <div className='col-lg-6'> 
       <div className='well'> 
        <ReactHighStock config={this.state.chartConfig} /> 
       </div> 
      </div> 
     ); 
    } 

    renderChart() { 
     var that = this; 
     NanoAjax.ajax({ 
      url: 'myApi.com?param1=' + this.state.apiParam1 + '&param2=' + this.state.apiParam2; 
     }, function (statusCode, responseText) { 
      //transform the data a bit 

      var chartConfig = that.getChartConfig(that.state.apiParam1); 
      chartConfig.series[0].data = chartData; 

      that.setState({ 
       chartConfig: chartConfig 
      }) 
     }); 
    } 

    getChartConfig(param1) { 
     // returns HighCharts chartConfig object based on apiParam1 
    } 
} 

이 한 구성 요소가 params를 초기 렌더링하는 동안 설정 즉, 일단 정적으로 완벽하게 잘 작동, 부모 제어를 업데이트하지 않습니다. 여기에 주어진 또한,이 방법은 동일합니다 : https://daveceddia.com/ajax-requests-in-react/

하지만, 내 요구 사항은 부모 컨트롤이 값 다시와 신선한 아약스 통화를 할 그것을 일으키는 원인이되는 소품 param1과이 컨트롤의 param2를 업데이트 할 수 있다는 것입니다 - 새로운 데이터로 차트를 렌더링합니다.

어떻게 접근하나요?

답변

2

솔루션은 요구 사항이 param1param2 변경하면 차트를 다시 쓰게하는 동안 구성 요소가

componentDidMount() { 
    this.renderChart(); 
} 

장착 된 경우에만 차트를 렌더링합니다. 이를 위해 우리는 당신이 값을 비교한다 componentWillReceiveProps을 사용하고 또한 그에 따라

componentWillReceiveProps(nextProps) { 
    let shouldRerenderChart = false; 

    shouldRerenderChart = shouldRerenderChart || this.props.propData.param1 !== nextProps.propData.param1; 

    shouldRerenderChart = shouldRerenderChart || this.props.propData.param2 !== nextProps.propData.param2; 

    if (shouldRerenderChart) { 
    this.renderChart(); 
    } 
} 

행동, 당신의 componentDidMount 기능을 유지,

장착시 초기 소품 componentWillReceiveProps를 호출하지 않습니다 반작용 때문에 수 있습니다. 당신은 유사한 방식으로 componentDidUpdate를 사용할 수있는 대안으로


.

+0

그러나 일반적으로'will'을 포함하는 함수가'setState'를 호출 스택에서 호출 할 수 없기 때문에'renderWartReceiveProps'에서'renderChart'를 호출 할 수 있습니까? –

+1

componentWillReceiveProps는 setState를 호출하려는 위치이며 두 번 다시 렌더링을 트리거하지 않습니다. 공식 문서에서 확인하십시오. componentWillReceiveProps()는 탑재 된 구성 요소가 새 소품을 받기 전에 호출됩니다. 소품 변경 (예 : 재설정)에 대한 응답으로 상태를 업데이트해야하는 경우 this.props와 nextProps를 비교하고이 메서드에서 this.setState()를 사용하여 상태 전이를 수행 할 수 있습니다. – lustoykov

+0

이제 시도해보십시오 :) –

관련 문제