gpt4 book ai didi

reactjs - 类型错误 : Cannot read property 'map' of undefined iwith react-redux

转载 作者:行者123 更新时间:2023-12-04 10:52:34 25 4
gpt4 key购买 nike

我遵循 react-redux 教程并尝试显示帖子。我从 https://jsonplaceholder.typicode.com/posts 获取帖子数据.它返回这样的响应:

enter image description here

import React from 'react';
import { connect } from 'react-redux';
import { fetchPost } from '../actions'

class PostList extends React.Component{
componentDidMount(){
this.props.fetchPost();
}
renderList(){
return this.props.post.map(pos => {
return (
<div className="item" key={pos.id}>
<p>{pos.title}</p>
</div>
);
});
}
render(){
return(<div className="ui relaxed divided list"> {this.renderList()} </div>);
}
}
const mapStateToProps = (state) =>{
return { post:state.post}
}
export default connect(mapStateToProps , { fetchPost })(PostList);

这是我的 Action 创建者
import JsonPlaceHolder from '../apis/JsonPlaceHolder'
export const fetchPost = () => {
return async (dispatch) => {
const response = await JsonPlaceHolder.get('/posts');
dispatch({
type: 'FETCH_POST',
payload:response
});
}
};

这是我的 reducer
export default (state=[],action) => {
switch(action.type){
case "FETCH_POST":
return action.payload;
default:
return state;
}
};

这是我的 ../apis/JsonPlaceHolder 文件
import axios from 'axios';

export default axios.create({
baseURL:"https://jsonplaceholder.typicode.com/"
});

但我收到这样的错误

TypeError: this.props.post.map is not a function

最佳答案

我想,你应该检查一下,你是否有this.props.post与否,在映射之前,因为请求需要一些时间,在此过程中您可能会收到 undefined值来自 this.props.post .

另外,如果你想映射 this.props.post ,那么你应该作为有效载荷返回,而不仅仅是 response ,但是 response.data .否则,你会得到一个错误,该对象没有方法 map .

关于reactjs - 类型错误 : Cannot read property 'map' of undefined iwith react-redux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59405552/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com