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