首页 > 解决方案 > 来自ajax的反应选择选项数据

问题描述

使用

<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})
}

一切正常,但选中显示如下

图片

怎么修?

标签: reactjsreact-material

解决方案


尝试并设置选定的值


<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>

推荐阅读