gpt4 book ai didi

javascript - this.props 不是父组件和子组件之间的函数

转载 作者:行者123 更新时间:2023-12-01 01:36:54 24 4
gpt4 key购买 nike

设置一个简单的帖子组件后,如果能够从帖子中获取评论,那就太酷了。

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;

之后,放置一个评论组件以使日志中的帖子评论开始显示

TypeError: this.props.getComments is not a function

enter image description here

那么,不能从函数传递 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;

最佳答案

您没有将该函数作为 props 传递给 Comments。

您必须将函数作为 prop 传递,如下所示:

<Comments getComments={this.getComments} />

关于javascript - this.props 不是父组件和子组件之间的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52749015/

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