设置一个简单的帖子组件后,能够从帖子中获取评论会很酷。
import React, { Component } from "react";
import axios from "axios";
import Comments from "../components/comments";
class Post extends Component {
constructor(props) {
super(props);
this.state = {
comments: [],
};
}
componentDidMount() {
this.getComments();
}
getComments() {
return axios
.get("/posts/" + this.props.match.params.id + "/comments")
.then(result => this.setState({ comments: result.data.comments }))
.catch(error =>
this.setState({
error
})
);
}
render() {
return (
<div>
<h2>Comments</h2>
<Comments />
</div>
);
}
}
export default Post;
所以之后,放置一个评论组件,让日志中的帖子评论开始显示
类型错误:this.props.getComments 不是函数
那么,是不是可以从函数中传递 props 呢?有人知道为什么会发生这个问题吗?
评论部分
import Comment from "./comment";
import axios from "axios";
import Post from "../screens/posts";
class Comments extends Component {
constructor(props) {
super(props);
this.state = {
comments: [],
error: ""
};
this.load = this.load.bind(this);
}
componentDidMount() {
this.load();
}
load() {
return this.props.getComments().then(comments => {
this.setState({ comments });
return comments;
});
}
render() {
return (
<div>
{this.state.comments.map(comment => (
<Comment key={comment.id} comment={comment} />
))}
</div>
);
}
}
export default Comments;
您没有将该函数作为道具传递给 Comments。
您必须像这样将函数作为道具传递:
<Comments getComments={this.getComments} />
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句