简体   繁体   English

this.props.firstCard返回未定义

[英]this.props.firstCard returns undefined

I'm new to react.js and I'm trying to math.random a number and put it in this.props.firstCard property, but it returns undefined. 我是React.js的新手,我想对一个数字进行math.random并将其放在this.props.firstCard属性中,但它返回未定义的值。 I tried some variables but only result is undefined or syntax error. 我尝试了一些变量,但结果是未定义的或语法错误。 Code: 码:

handleClick() {
let firstCard = this.state.isFirstCardChosen;
function chooseCard() {
  return Math.floor(Math.random() * (80 - 1) + 1);
}
if (firstCard == false) {
  this.props.firstCard = chooseCard;
  console.log(this.props.firstCard);
}
}

What's wrong with this one? 这是怎么了 Thanks in advance. 提前致谢。

I'm going to hazard a guess and suggest that 我要冒险猜一个建议

if: 如果:

the problem isn't just one caused by the fact you are trying to mutate props ( props are immutable ). 问题不仅仅是由您试图更改道具( 道具是不可变的 )引起的。

and: 和:

You're using ES2015 class syntax 您正在使用ES2015类语法

then 然后

the problem may be that your handleClick method isn't properly bound to the component state so the call to this.props returns undefined . 问题可能是您的handleClick方法未正确绑定到组件状态,因此对this.props的调用返回undefined

To solve this you can bind the handleClick in the constructor as follows: 为了解决这个问题,您可以按以下方式在构造函数中绑定handleClick

constructor (props){
  super(props);
  this.handleClick = this.handleClick.bind(this);
}

As everyone else has said the props is immutable. 正如其他人所说的,道具是一成不变的。 Also make sure you are setting props correctly and binding your handleClick function in your constructor ie: 还要确保正确设置道具并在构造函数中绑定handleClick函数,即:

constructor(props) {
    super(props);
    his.handleClick = this.handleClick.bind(this);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM