React-如何重新渲染视图而不是附加视图?

时间:2016-12-20 00:11:23

标签: reactjs

每次用户点击不同的时间范围时,我都会从API获取数据。我试图根据时间框架更新一些表格和图表。但是,它不会重新渲染当前图形并更新(或删除和读取),而是附加到我的视图中。

我可以做些什么来重新渲染我的视图而不是追加到它?

代码:

import React from 'react';
import {LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend} from 'recharts';
import axios from 'axios';
import {Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn} from 'chroma-fx/build/Table';
import Button from 'react-bootstrap/lib/Button';
import ButtonGroup from 'react-bootstrap/lib/ButtonGroup';

var array = []
var button_value = 1

var StatisticsPage = React.createClass({
  getInitialState: function() {
     return {info: "loading ... "};
  },
  componentDidMount: function() {
     this.requestStatistics(button_value);
  },
  render: function() {
    var statisticsComponents = array.map(function(stat, i) {
          var result = stat['Value']
          var heading = stat['Name']

          var state = {
            showCheckboxes: false,
            height: '300px',
            width:'300px'
          };
          return ();
       });
    var buttonComponents = <ButtonGroup>
      <Button onClick={() => this.onButtonClick(16)}>4 months</Button>
      <Button onClick={() => this.onButtonClick(4)}>1 month</Button>
      <Button onClick={() => this.onButtonClick(1)}>1 week</Button>
    </ButtonGroup>

    return <div>{buttonComponents}{statisticsComponents}</div>;
  },
  onButtonClick: function(value){
    button_value = value
    this.requestStatistics(button_value)
  },
  requestStatistics:function(button_value){
      axios.post('api/2/statistics', button_value, {
            headers: {
                'Content-Type': 'application/json'
            }
        } )
      .then(res => {
        var values = res['data']
        for (var value in values){
            array.push({Name: value, Value: values[value] })
        }
        this.setState(array)
      });
    }
  })

const View = () => (
    <div>
    <h1>Reports</h1>
    <StatisticsPage stations={array} />
    </div>
);
export default View;

1 个答案:

答案 0 :(得分:2)

首先在回调中清空数组。

axios.post('api/2/statistics', button_value, {
        headers: {
            'Content-Type': 'application/json'
        }
    } )
  .then(res => {
    var array = []
    var values = res['data']
    for (var value in values){
        array.push({Name: value, Value: values[value] })
    }
    this.setState(array)
  });
}