我想从数据库中显示"referti“到我的select下拉列表中,但是我一直收到同样的错误"this.state.referti.map不是一个函数”。代码如下:
componentDidMount() {
this.mostraReferti(account.id)
}
mostraReferti(id) {
axios.get('http://localhost:8080/api/REFERTOs/' + id)
.then(response => {
this.setState({ referti: response.data }, () => {
console.log("response.data", response.data)
console.log("THIS.STATE", this.state)
})
})
.catch(err => console.log(err))
}
render() {
const refertiItems = this.state.referti.map((referti, i) => {
return (
<RefertiItems key={referti.hash_referto} item={referti} />
)
})
<Label for="type" text="Referto" />
<div className="custom-select">
{refertiItems}
</div>现在,response.data是一个对象,但是当我将它存储在状态引用中时,console.log ( "THIS.STATE")说它是一个数组,所以它应该被映射,但我仍然得到"this.state.referti.map“不是一个函数。RefertiItems是:
class RefertiItems extends Component {
constructor(props) {
super(props);
this.state = {
item: props.item
}
}
render(){
return (
<div className= "custom-select">
<Label for="type" text="Codice Referto" />
<select
name="codiceReferto"
placeholder="Selezionare Referto"
onKeyPress={this.onEnter} //allows you to move to the next panel with the enter key
value={this.codiceReferto}
onChange={this.handleInputChange}>
<option default value="vuoto"></option>
<option>{this.state.item.tipo_esame}-
{this.state.item.data_esame}</option>
</select>
</div>
)}
}奇怪的是,一开始我得到了错误,页面没有加载,但如果我重新加载代码,系统会呈现页面,我得到了4个不同的选择,每个选择都有一个不同的值。
发布于 2019-09-02 22:43:39
这看起来像是由于您没有初始状态而导致的问题。将以下内容添加到您的组件中,您的问题就会消失:
state = { referti: [] }这将确保.map最初会选择[],而不是undefined
发布于 2019-09-02 22:41:31
使用条件渲染,因为setState是一个async进程,所以不能保证在调用render时数据会在那里,进行以下更改,它应该可以工作:
确保referti是可迭代的,会抛出错误,因为map只适用于arrays。此外,请确保将referti设置为[]作为initial state.
示例沙盒:https://codesandbox.io/s/compassionate-worker-rk7z4?fontsize=14
您的状态对象:
state = {
referti: []
}条件渲染:
const refertiItems = this.state.referti.length > 0 && this.state.referti.map(referti => <RefertiItems key={referti.hash_referto} item={referti} /> />);https://stackoverflow.com/questions/57758779
复制相似问题