为什么此代码显示“未定义”而不是StarRating组件?

时间:2020-06-05 19:24:09

标签: reactjs react-state

import React, { Component } from "react";
import Star from "./Star";

class StarRating extends Component {
  constructor(props) {
    super(props);
    this.state = {
      rating: 0,
      stars: this.returnStars(),
    };
    this.getStars = this.getStars.bind(this);
  }
  getStars() {
    console.log(this);
  }
  returnStars() {
    const stars = [];
    for (let i = 0; i < 5; i++) {
      const star = <Star handleStar={this.getStars} />;
      stars.push(star);
    }
    return stars;
  }

  render() {
    return <ul className="course--stars">{this.state.stars}</ul>;
  }
}

export default StarRating;

// This is Star component
import React from "react";

const Star = (props) => {
  return (
    <li onClick={props.handleStar}>
      <svg x="0px" y="0px" viewBox="0 0 16 15" className="star">
        <path
          d="M8.5,0.3l2,4.1c0.1,0.2,0.2,0.3,0.4,0.3l4.6,0.7c0.4,0.1,0.6,0.6,0.3,0.9l-3.3,3.2c-0.1,0.1-0.2,0.3-0.2,0.5l0.8,4.5
      c0.1,0.4-0.4,0.8-0.8,0.6l-4.1-2.1c-0.2-0.1-0.3-0.1-0.5,0l-4.1,2.1c-0.4,0.2-0.9-0.1-0.8-0.6l0.8-4.5c0-0.2,0-0.4-0.2-0.5L0.2,6.2
      C-0.2,5.9,0,5.4,0.5,5.3L5,4.7c0.2,0,0.3-0.1,0.4-0.3l2-4.1C7.7-0.1,8.3-0.1,8.5,0.3z"
        />
      </svg>
    </li>
  );
};

export default Star;
在Star组件上调用onClick函数时,getStars()会记录未定义的日志,而不是StarRating类的日志?

并且当我使用这种语法渲染Star组件时,它就可以正常工作并记录StarRating

render() {
    return <ul className="course--stars">{this.returnStars()}</ul>;
  }

我不是我做错了。

1 个答案:

答案 0 :(得分:1)

我只是看了看你的代码,我认为这就是原因。在绑定returnStars()函数之前,可以设置stars状态变量的值。尝试声明状态变量时,首先将初始值设置为[]并在组件安装中设置。

为避免这种情况,请尝试在componentDidMount上设置星星,然后在安装它之前将returnStars绑定,然后它将起作用。

componentDidMount() {
    this.setState({stars: this.returnStars()})
}

希望这可以帮助您理解!