gpt4 book ai didi

javascript - react 类型错误 : Cannot read property 'map' of undefined on passing props

转载 作者:行者123 更新时间:2023-12-04 00:58:55 24 4
gpt4 key购买 nike

从post组件获取comments数组后传给comments组件日志开始在下面的屏幕截图中显示错误

enter image description here

组件是:

import React, { Component } from "react";
import axios from "axios";

import Comments from "../components/comments";

class Article extends Component {
constructor(props) {
super(props);

this.state = {
title: "",
error: "",
comment: ""
};
}

componentDidMount() {

this.getComments();
}


getComments = () => {
const {
match: { params }
} = this.props;

return axios
.get(`/articles/${params.id}/comments`, {
headers: {
Accept: "application/json",
"Content-Type": "application/json",

}
})
.then(response => {
return response.json();
})
.then(response => this.setState({ comments: response.comments }))
.catch(error =>
this.setState({
error
})
);
};



render() {
return (
<div>
{this.state.title}
<div>
<h2>Comments</h2>
<Comments
getComments={this.getComments}

/>
</div>

</div>
);
}
}

export default Article;

和评论组件

import React, { Component } from "react";
import PropTypes from "prop-types";
import Comment from "./comment";
import axios from "axios";

import Article from "../screens/article";

class Comments extends Component {
constructor(props) {
super(props);
this.state = {
comments: [],

comment: "",
error: ""
};

this.load = this.load.bind(this);

this.comment = this.comment.bind(this);
}

componentDidMount() {
this.load();
}

load() {
return this.props.getComments().then(comments => {
this.setState({ comments });

return comments;
});
}

comment() {
return this.props.submitComment().then(comment => {
this.setState({ comment }).then(this.load);
});
}

render() {

const { comments } = this.state;

return (
<div>
{comments.map(comment => (
<Comment key={comment.id} commment={comment} />
))}
</div>
);
}
}



export default Comments;

所以,我尝试通过 props 传递它,并在评论组件上设置状态。而不是只使用 comments.map 我尝试使用 this.state 但在日志中显示相同的错误。那么,有人想澄清这种问题吗?使用 React 时似乎很常见。

最佳答案

如果发生错误,您可以:

  .catch(error =>  this.setState({ error  }) );

这使得链式 promise 解析为 undefined 并且在 Comments 状态下用作 comments。所以你必须从捕获中返回一个数组:

 .catch(error => {
this.setState({ error });
return [];
});

此外,如果父级状态包含错误,则完全不呈现 Comments 子级是有意义的。

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

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