【问题标题】:React Select options data from ajax来自ajax的反应选择选项数据
【发布时间】:2021-01-16 02:25:49
【问题描述】:

使用

<Select
    native
    value={item.resolution}
    onChange={this.handleChange}
    inputProps={{
        name: 'student',
        id: 'student',
        data_id: index
    }}
>
    { this.state.students ? this.state.students.map((res, i) => (
        <option key={index+i} value={res.id}>{res.name}</option>
    )): ''}
</Select>

在构造函数中

constructor(props) {
    super(props);
    this.state = {
        students: []
    }
}

componentDidMount() {
    this.getOptions()
}

async getOptions(){
    const res = await axios.get('https://jsonplaceholder.typicode.com/users')
    const data = res.data

    const options = data.map(d => ({
        "value" : d.id,
        "label" : d.name
    }))
    this.setState({students: options})
}

一切正常,但选择如下所示

如何解决?

【问题讨论】:

标签: reactjs react-material


【解决方案1】:

也尝试设置选定的值


<Select
    native
    value={item.resolution}
    onChange={this.handleChange}
    inputProps={{
        name: 'student',
        id: 'student',
        data_id: index
    }}
>
    { this.state.students ? this.state.students.map((res, i) => (
        <option key={index+i} value={res.id} selected={i === 0}>{res.name}</option>
    )): ''}
</Select>

【讨论】:

    【解决方案2】:

    如果学生等于选项,那么学生将只有值和标签属性

    const options = data.map(d => ({
        "value" : d.id,
        "label" : d.name
    }))
    

    res.id 和 res.name 应该是未定义的

     <option key={index+i} value={res.id} selected={i === 0}>{res.name}</option>
    

    编辑:建议

    我认为这行:

    this.state.students ? this.state.students.map((res, i) => (
            <option key={index+i} value={res.id} selected={i === 0}>{res.name}</option>
        )): ''
    

    这样会更好看:

    this.state.students && this.state.students.map((res, i) => (
            <option key={index+i} value={res.id} selected={i === 0}>{res.name}</option>))
    

    【讨论】:

      【解决方案3】:

      解决了这个问题

      constructor(props) {
              super(props);
              this.state = {
                  loading: true
              }
      }
      

      然后

      {!this.state.loading? this.props.items.map((item, index) => (
      
      ))}
      

      【讨论】:

        猜你喜欢
        • 2021-08-16
        • 2018-07-31
        • 2017-07-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-25
        • 2019-09-23
        相关资源
        最近更新 更多