如何在setState回调的回调中进行axios调用

时间:2018-11-23 04:13:28

标签: javascript

我有两个异步调用,如下所示。我尝试将axios调用包装在this.setState的回调中,但是会引发类似, expected

的语法错误
      this.setState(prevState => ({ 
          condition: [...prevState.condition, { name: "readByGroup", operator: "IN  ", value: groups }]
        }))
      }

        this.props.getMetricsByContent(this.state.condition).then((data) => {
          this.setState({isLoader: false});
          if(data && Array.isArray(data) && data.length > 0){
            let csvContent = papa.unparse(data);
            this.download(csvContent, 'metrics.csv', 'text/csv;encoding:utf-8');
            this.setState({statusMsg: "File Downloaded successfully"})
          } else this.setState({statusMsg: "No records to download"})
        })

我尝试的内容如下:

this.setState(prevState => ({ 
      condition: [...prevState.condition, { name: "readByGroup", operator: "IN  ", value: groups }]

      this.props.getMetricsByContent(this.state.condition).then((data) => {
        this.setState({isLoader: false});
        if(data && Array.isArray(data) && data.length > 0){
          let csvContent = papa.unparse(data);
          this.download(csvContent, 'metrics.csv', 'text/csv;encoding:utf-8');
          this.setState({statusMsg: "File Downloaded successfully"})
        } else this.setState({statusMsg: "No records to download"})
      })
}))

1 个答案:

答案 0 :(得分:1)

我看不到您在this.setState中运行回调函数的位置。

尝试:

   this.setState(prevState => ({ 
          condition: [...prevState.condition, { name: "readByGroup", operator: "IN  ", value: groups }]
    }),  () => {
     this.props.getMetricsByContent(this.state.condition).then((data) => {
            this.setState({isLoader: false});
            if(data && Array.isArray(data) && data.length > 0){
              let csvContent = papa.unparse(data);
              this.download(csvContent, 'metrics.csv', 'text/csv;encoding:utf-8');
              this.setState({statusMsg: "File Downloaded successfully"})
            } else this.setState({statusMsg: "No records to download"})
          }))
   }

键是箭头,它是setState的下一个参数。

https://reactjs.org/docs/react-component.html#setstate