您好,我正在从 api 获取数据,我想获取数据并将其渲染到 dom,但出现错误“Uncaught TypeError: Cannot read property 'map' of undefined at Topicselect.render”
这基本上就是我正在做的事情,尽管我已经抽象出了与问题不直接相关的任何内容,例如实际的主题名称、导入等:
class Topics extends Component{
constructor(props){
super(props);
this.state = {
topics: []
}
}
componentWillMount(){
fetch('/api').then((res)=>r.json().then((data)=>{
// push topics into this.state.topics somehow
})
console.log(this.state.topics) //returns ['topic1','topic2','topic3'];
}
render(){
const list = this.state.topics.map((topic)=>{
return(<li>{topic}</li>);
})
return(
<ul>
{list}
</ul>
)
}
}
谁能告诉我如何解决这个问题?我在这里看到一个答案,说使用 componentDidMount 而不是 componentWillMount 但这对我不起作用
您缺少右括号)
获取后确实建议使用componentDidMount()
代替componentWillMount()
用于从 API 获取数据。
也不要忘记使用this.setState({ topics: data.howeverYourDataIsStructured });
从 API 收到数据后,以确保组件的重新呈现。
class Topics extends Component{
constructor(props){
super(props);
this.state = {
topics: []
}
}
componentDidMount() {
fetch('/api').then((res)=>r.json().then((data)=>{
this.setState({ topics: data.topics });
}));
console.log(this.state.topics) //returns [];
}
render() {
console.log(this.state.topics) //returns [] the first render, returns ['topic1','topic2','topic3'] on the second render;
return(
<ul>
{this.state.topics.map(topic => (
<li>{topic}</li>
))}
</ul>
)
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)