class Schoolextends React.Component {
constructor(){
super();
this.state = {
schoolName:[]
}
}
getMySchools(){
let arraySchools=[];
const db=fire.firestore();
db.collection("schoolNames").get().then((snapshot)=>{
snapshot.forEach((doc)=>{
// console.log(doc.data())
// return(<option>{doc.data()}</option>)
arraySchools.push(doc.data())
})
this.setState({schoolName:arraySchools})
})
}
componentDidMount(){
this.getMySchools();
}
render(){
return (
<Form.Group controlId="exampleForm.ControlSelect1">
<Form.Label>Select Schools</Form.Label>
<Form.Control as="select" onChange={(e) => this.setState({schoolName: e.target.value})}>
<option></option>
{this.state.schoolName.map((index)=>{
return(<option value={index.addSchool}>{index.addSchool}</option>)
})}
</Form.Control>
)
}
}
在上面的代码中,我从中获取学校的名称,firestore
并将其填充在选择下拉列表中。并且在选择任何选项时,它会将值存储在schoolName
对象数组中作为setState,但会抛出错误TypeError: this.state.schoolName.map is not a function
。
这是因为您在此处将其设置为字符串:
onChange={(e) => this.setState({schoolName: e.target.value})}
然后尝试映射不可能的字符串
您需要this.state.schoolName
使用一组对象更新状态,然后在其上进行映射。
或根本不映射它,而只是将其引用为渲染中的对象
只是将其更新为对象
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句