这是一个菜鸟问题,所以请放纵。任何帮助深表感谢。我有下拉选择字段household
,我需要从数组list
填充。数组list
最初是空白的,并从函数getHouses
(这是一个API get调用)中填充。如何使用该数组填充我的选择字段?
功能getHouses
:
const List = []
function getHouses() {
let token = localStorage.getItem('id_token') || null;
const AuthStr = 'Bearer '.concat(token);
axios.get(BASE_URL + 'household/list', { headers: { Authorization: AuthStr } }).then(function (response) {
console.log(response);
let myData = response.data;
console.log(myData);
for (let i = 0; i < myData._embedded.length; i++) {
let embedded = myData._embedded[i];
List.push(embedded.friendlyName);
}
console.log(List);
//this.setState({data:list});
}).catch((error) => {
console.log('error' + error);
});
}
select
字段
<Field name="family" component={renderDropdownList} data={List} label="family" className="form-control" placeholder="select your family" />
我需要做什么?我还不擅长管理国家(初学者),所以我非常困惑。
renderDropDownList
export const renderDropdownList = ({ input, data, valueField, textField }) =>
<DropdownList
{...input}
data={data}
valueField={valueField}
textField={textField}
onChange={input.onChange}
/>;
编辑:正如Prakash建议的那样,我尝试制作一个组件并设置状态,但这会让我在控制台中Cannot read property 'setState' of undefined
。这是我的组成部分:
class Location extends Component {
constructor(){
super();
this.state = {
data: []
};
this.getHouses = this.getHouses.bind(this);
}
componentDidMount() {
this.getHouses()
}
getHouses = (e) => {
let token = localStorage.getItem('id_token') || null;
const AuthStr = 'Bearer '.concat(token);
axios.get(BASE_URL + 'household/list', { headers: { Authorization: AuthStr } }).then(function (response) {
console.log(response);
let myData = response.data;
console.log(myData);
let list =[]
for (let i = 0; i < myData._embedded.length; i++) {
let embedded = myData._embedded[i];
list.push(embedded.friendlyName);
}
console.log(list);
this.setState({data:list});
})
.catch((error) => {
console.log('error' + error);
});
}
render()
{
return(
<div>
<Field
name="family"
type="text"
component={renderDropdownList}
data={this.state.list}
label="family"
className="form-control"
placeholder="select your family"
/>
</div>
)
}
}