即使使用箭头功能也无法设置状态

时间:2019-03-27 21:39:21

标签: reactjs fetch react-chartjs

我是具有React的初学者,并且我尝试使用fetch api。我想从api获取一些有关人口的数据。我已经设法检索了数据,但是当我尝试在访存中使用setState时,图表不会使用新数组进行更新。下面是我来自app.js的代码,希望这是足够的信息:

class App extends Component {

  constructor(){
    super();
    this.state = {
      chartData:{}
    }
  }

  componentWillMount(){
    this.getChartData();
  }

  getChartData(){
    let queryPost = {
    "query": [
      {
        "code": "Region",
        "selection": {
          "filter": "vs:RegionLän07",
          "values": [
            "01"
          ]
        }
      },
      {
        "code": "ContentsCode",
        "selection": {
          "filter": "item",
          "values": [
            "BE0101N1"
          ]
        }
      }
    ],
    "response": {
      "format": "json"
    }
    }

    fetch('https://api.scb.se/OV0104/v1/doris/sv/ssd/START/BE/BE0101/BE0101A/BefolkningNy'
    ,{
    method:'post',
    body:JSON.stringify(queryPost),
    })

    .then(response => response.json())
    .then(result => result.data.map(obj => (
    parseInt(obj.values[0])
    )))
    .then(newArr => this.setState({chartData:{
      labels:['dsa','cava','daba','baba'],
      datasets:[
        {
        label:'Populations',
        data: [newArr[0],newArr[1],newArr[2]],
        backgroundColor:[
            'rgba(255,99,132,0.6)',
            'rgba(100,100,2,0.6)',
            'rgba(10,100,2,0.6)',
        ],
        }
      ]
    }},console.log(this.state.chartData))
    )}   

  render(){
    return (
    <div className="content">
      <div className="row justify-content-center align-items-center header">
        <h1>Befolkningsinfo</h1>
      </div>
      <div className="row">
        <div className="col-md-6 col-sm-12">
          <div className="App">

          </div>
        </div>
        <div className="col-md-6 col-sm-12">
          <div className="App">
            <BarChart chartData={this.state.chartData} title='Chart1'/>
          </div>
        </div>
      </div>
      <div className="row">
        <div className="col-md-6 col-sm-12">
          <div className="App">

          </div>
        </div>
        <div className="col-md-6 col-sm-12">
          <div className="App">
            <PieChart chartData={this.state.chartData} title='Chart2'/>
          </div>
        </div>
      </div>
    </div>
    )
  }
}

export default App;

1 个答案:

答案 0 :(得分:0)

您要在componentDidMount中调用提取。在调用componentDidMount时,该组件已被渲染一次。

实际上,componentDidMount是发出调用以获取数据的最佳位置,其原因有两个: 使用didMount可以清楚地表明,只有在初始渲染之后才会加载数据。这提醒您正确设置初始状态,以免最终导致出现错误的未定义状态。

如果您需要在服务器上呈现您的应用程序,componentWillMount实际上将被调用两次-一次在服务器上,再一次在客户端上-这可能不是您想要的。将您的API调用代码放在componentDidMount中,可以确保仅从客户端获取数据,而应该从客户端获取数据。

相关问题