[英]Axios request fails which fires Cannot read property 'map' of undefined
I am working on a blog post project.我正在做一个博客文章项目。 I have a method renderPostList() that renders a list of posts.
我有一个渲染帖子列表的方法 renderPostList()。 I am using the .map function on the array.
我在数组上使用 .map 函数。 When I access /post/list route, the Axios request is not firing and there is nothing in the redux store.
当我访问 /post/list 路由时,Axios 请求没有触发,并且 redux 存储中没有任何内容。 Therefore, undefined.map() is called that causes this error.
因此,调用 undefined.map() 会导致此错误。 The console.log(this.props.posts) is returning an empty array due to request failure.
由于请求失败,console.log(this.props.posts) 返回一个空数组。 Even if I write a conditional of "if(this.props.posts)" the method still executes the .map on the undefined array.
即使我写了一个“if(this.props.posts)”的条件,该方法仍然在未定义的数组上执行 .map 。 Is there a way to make this work correctly?
有没有办法使这项工作正常进行? I need the data to be passed before .map executes.
我需要在 .map 执行之前传递数据。 And why the conditional is not working?
为什么条件不起作用?
componentDidMount() {
this.props.getPosts();
this.setState({
items: this.props.posts.filter(function (post) {
return post.isRelated === false;
}).length,
});
}
renderPostList() {
if (this.props.posts) { //not working conditional
console.log(this.props.posts);
let filtered_posts = this.props.posts.filter(function (post) {
return post.isRelated === false;
});
var postChunks = this.chunkArray(filtered_posts, 3);
return postChunks[this.state.activePage - 1].map(
({ title, meta_info, timestamp, img, id }) => {
return (
<div className="item" key={id}>
<Post
title={title}
meta_info={meta_info}
timestamp={timestamp}
img={img}
/>
</div>
);
}
);
}
return null;
}
const mapStateToProps = (state) => {
return { posts: state.posts };
};
export default connect(mapStateToProps, { getPosts })(News);
Action行动
export const getPosts = () => async (dispatch) => {
const response = await api.get("post/list");
dispatch({ type: "GET_POSTS", payload: response.data });
};
Reducer减速器
export default (state = [], action) => {
switch (action.type) {
case 'GET_POSTS':
return action.payload;
default:
return state;
}
};
Axios instance axios 实例
export default axios.create({
baseURL: dev_url,
headers: {
"X-Requested-With": "XMLHttpRequest",
},
});
I will appreciate any feedback on this code.我将不胜感激对此代码的任何反馈。 Thanks!
谢谢!
The condition will pass cause javascript script returns true for an empty array.条件将通过,导致 javascript 脚本为空数组返回 true。 the condition should be
条件应该是
if(this.props.post.length)
if the array length is zero the condition will not pass.如果数组长度为零,则条件不会通过。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.