javascript - this.props is not a function between parent and children components
问题描述
After setup a simple post component, it would be cool to be able to get the comments from the post.
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;
so after, place a comment component to get the post comments in the logs start to show
TypeError: this.props.getComments is not a function
So, is not possible to pass props from function? someone has any idea why this issue happen?
the comments component
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;
解决方案
You are not passing the function to Comments as a prop.
You must pass the function as a prop like this:
<Comments getComments={this.getComments} />
推荐阅读
- excel - 在具有重复日期的日期范围内查找最小日期
- google-bigquery - 拆分逗号分隔的字符串并使用 Bigquery 将第二列的值划分为单独的行
- typescript - 通用和“任何”的交集类型不会缩小属性范围
- ruby-on-rails - 添加路线后头像不显示
- angular - 如何以角度模拟切片管
- python - unpickling 类实例时不断收到“Property object at 0x”
- python - 使用步长值切片日期/时间
- qt - QML Listview space items to fill width
- flutter - 如何在 Flutter 视频播放器上使用 setState
- javascript - 有没有办法使用 Next.js 动态导入来导入函数?Next.js ssr 的 react-component-export-image 问题