React未使用setState装载选项标记



如果reactstate没有提取react bootstrapselect表单控制标记中的数据,我会遇到问题。以下是我到目前为止所做的:

状态结构

this.state = {
... more list
list: [] // in this list, each item contains { id: 1, name: 'some name' }
}

某些类别

componentDidMount() {
// ...api fetch and here 
axios.get('https://api-server.com/test/on/something').then(response => {
this.setState(state => {
response.data['something'].map(g => {
return state.list.push(g);
})
}, () => {
console.log(this.state.list) // it did set the state
})
});
}

render((

<Form.Control as="select">
{
// the problem is here! can't extract the data
this.state.list.map(g => {
return <option value={g.id}>{g.name}</option>
})
}
</Form.Control>

我不确定它为什么没有显示每个数据,但我确信它确实正确地设置了state中的每个项目。

您正在更改现有状态state.list.push(g);,这在React中是不应该完成的。这不是一个好办法。

尝试这样的方法,克隆所有内容:

this.setState(prevState => ({ ...prevState, list: [ ...prevState.list, ...response.data['something'] ] }))

我刚试过你的API URL,但没有返回任何内容。

你能检查一下你的控制台,看看它是否返回了什么吗?