首页 > 解决方案 > 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

enter image description here

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;

标签: javascriptreactjs

解决方案


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} />

推荐阅读