React-select 下拉框不渲染数据
React-select dropdown does not render data
我正在尝试使用 react-select 进行下拉。 console.log
将我的 subjectList
数组显示为 [object object],[object,object]... 如果我不使用 react-select
,我的下拉列表可以正常显示。我不知道问题出在哪里。下面是我的代码:
import React, {Component} from 'react';
import axios from 'axios';
import Select from 'react-select';
class Subject extends Component{
state={subjectList:[]};
componentDidMount(){
this.getSubjects();
}
//get distinct subject
getSubjects= ()=>{
axios.get('/apiURL')
.then(response=>{
const subjects= response.data;
//remove duplicates
const subjectList = [...new Map(subjects.map(item => [item["SUBJECT"], item])).values()];
this.setState({subjectList: subjectList});
});
};
render(){
let subjectList=this.state.subjectList.map((item,i) => <option key={i} value={item.SUBJECT}>{item.CATEGORY}</option>);
return(
<Select options={subjectList} />
);
}
}
export default Subject;
如果我将 return 更改为以下代码,它可以正常工作。但我想为我的下拉菜单尝试 react-select。
return (
<div>
<select>
<option value=''>Select a subject</option>
{this.state.subjectList.map((item,indx)=><option key={indx} value={item.SUBJECT}>{item.CATEGORY}</option>)}
</select>
</div>
);
阅读 react-select
文档中的用法部分:https://github.com/JedWatson/react-select#installation-and-usage
在您的情况下,渲染中的 subjectList
应该是具有 'value' 和 'label' 键的对象数组,而不是 <option>
元素。所以像:
let subjectList = this.state.subjectList.map(item => ({value: item.SUBJECT, label: item.CATEGORY}));
你可以用来刷新
_defer(() => $(this.selectRef).selectpicker('refresh'));
我正在尝试使用 react-select 进行下拉。 console.log
将我的 subjectList
数组显示为 [object object],[object,object]... 如果我不使用 react-select
,我的下拉列表可以正常显示。我不知道问题出在哪里。下面是我的代码:
import React, {Component} from 'react';
import axios from 'axios';
import Select from 'react-select';
class Subject extends Component{
state={subjectList:[]};
componentDidMount(){
this.getSubjects();
}
//get distinct subject
getSubjects= ()=>{
axios.get('/apiURL')
.then(response=>{
const subjects= response.data;
//remove duplicates
const subjectList = [...new Map(subjects.map(item => [item["SUBJECT"], item])).values()];
this.setState({subjectList: subjectList});
});
};
render(){
let subjectList=this.state.subjectList.map((item,i) => <option key={i} value={item.SUBJECT}>{item.CATEGORY}</option>);
return(
<Select options={subjectList} />
);
}
}
export default Subject;
如果我将 return 更改为以下代码,它可以正常工作。但我想为我的下拉菜单尝试 react-select。
return (
<div>
<select>
<option value=''>Select a subject</option>
{this.state.subjectList.map((item,indx)=><option key={indx} value={item.SUBJECT}>{item.CATEGORY}</option>)}
</select>
</div>
);
阅读 react-select
文档中的用法部分:https://github.com/JedWatson/react-select#installation-and-usage
在您的情况下,渲染中的 subjectList
应该是具有 'value' 和 'label' 键的对象数组,而不是 <option>
元素。所以像:
let subjectList = this.state.subjectList.map(item => ({value: item.SUBJECT, label: item.CATEGORY}));
你可以用来刷新
_defer(() => $(this.selectRef).selectpicker('refresh'));