ReactJS渲染数组时报TypeError: Cannot read property 'map' of undefined
你遇到的TypeError: Cannot read property 'map' of undefined报错是由以下几处代码错误共同导致的:
- 渲染时取值路径错误:render方法中你直接读取
this.post,但post是存储在组件state中的属性,正确的读取路径应为this.state.post,访问不存在的this.post自然返回undefined,调用map方法就会抛出报错。 - state初始结构错误:你初始state中的post被定义为单个视频对象,但实际需要存储从接口拿到的视频数组,结构不匹配导致后续即使赋值正确也无法调用数组方法。
- 接口返回值处理逻辑错误:你拿到接口返回的videos数组后,遍历数组时每次都调用setState直接覆盖post的值,最终post只会保留数组最后一项的对象,永远不会是可遍历的数组。
修复后的完整Home组件代码
export default class Home extends Component{ constructor(props){ super(props); this.state = { redirect: null, // 修正:post初始化为空数组 post: [], currentUser: null, userReady: false }; } componentDidMount() { const currentUser = AuthService.getCurrentUser(); if(!currentUser) { this.setState({ redirect: "/login"}); return; } this.setState({ currentUser: currentUser, userReady:true}); PostService.return().then(result => { // 修正:直接把整个videos数组赋值给post,不需要遍历覆盖 this.setState({ post: result.data.videos }) }) } render(){ if(this.state.redirect){ return <Redirect to={this.state.redirect} /> } return( <div> {/* 修正:读取state里的post,加可选链避免数组未加载完成时报错 */} { this.state.post?.map((result) => ( <Post key={result._id} username={result.username} caption={result.title} vidUrl={result.vidUrl}/> )) } </div> ) } }
Post组件本身没有逻辑错误,无需修改。
内容的提问来源于stack exchange,提问作者Jack Micco
相关产品推荐
相关产品推荐

