【问题标题】:React select list from get method从 get 方法中反应选择列表
【发布时间】:2019-04-12 07:58:29
【问题描述】:

我对 React Select 有疑问。我正在使用 axios get 方法来获取下拉列表的数据,然后我想在 React Select 中显示它。

我从 github 示例中复制了代码,但它不起作用。

获取方法:

onListaDzial = () => {
  axios
    .get("http://10.10.10.27:81/eWizjaAPI/api/Listy/GetSlownikDzialy?", { params : {rok : this.state.rok }, headers: { 'Authorization' : 'Bearer '+ this.state.token }})
    .then(function (response) {
          let options = response.data.map( category => ({ value: category.text, label: category.text}));
          return { options };
}) 
    .catch(error => this.setState({ error,  }));

}

在渲染中反应选择代码


<Select name="form-field-name" options={options} />

【问题讨论】:

    标签: reactjs list select get axios


    【解决方案1】:

    您需要设置组件的状态才能在渲染函数中使用它。您还需要在.then 中使用箭头函数,否则 this 上下文是错误的!

    onListaDzial = () => {
      axios
        .get("http://10.10.10.27:81/eWizjaAPI/api/Listy/GetSlownikDzialy?", { params : {rok : this.state.rok }, headers: { 'Authorization' : 'Bearer '+ this.state.token }})
        .then((response) => {
          let options = response.data.map( category => ({ value: category.text, label: category.text}));
          this.setState({options});
      }).catch(error => this.setState({ error,  }));
    }
    

    在渲染中

    <Select name="form-field-name" options={this.state.options} />
    
    

    您还可以将 onListaDzial 函数重写为 async/await,如下所示:

    onListaDzial = async () => {
      const res = await axios.get("http://10.10.10.27:81/eWizjaAPI/api/Listy/GetSlownikDzialy?", { params : {rok : this.state.rok }, headers: { 'Authorization' : 'Bearer '+ this.state.token }}).catch(error => this.setState({ error,  }));
      let options = res.data.map( category => ({ value: category.text, label: category.text}));
      this.setState({options});
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-22
      • 1970-01-01
      • 1970-01-01
      • 2021-08-16
      • 2011-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多