2016-12-27 91 views
0

我是新來的react.js,我試圖math.random一個數字並把它放在this.props.firstCard屬性中,但它返回undefined。我嘗試了一些變量,但只有結果是未定義的或語法錯誤。代碼:this.props.firstCard返回undefined

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); 
} 
} 

有什麼不對的呢?提前致謝。

+0

SRY出現了一個'this.props.firstCard == chooseCard;'而不是「this.props.firstCard = chooseCard;」 ,它返回'不可擴展'的錯誤。 – zaebalo

+0

this.props是不可變的。你不能修改它。通過一些關於setState的反應教程和道具 –

回答

0

我要大膽地猜測和建議

如果:

的問題不只是一個造成您試圖變異道具(props are immutable)的事實。

和:

您使用ES2015類語法

然後

問題可以是你​​方法不正確綁定到組件狀態等等對this.props的呼叫返回undefined

爲了解決這個問題,你可以在構造結合​​如下:

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

我應該使用什麼語法呢? es2016? – zaebalo

+0

很難說,你可以在你使用_handleClick_的地方發佈代碼嗎? – Pineda

0

至於其他人說的道具是不可變的。另外,還要確保你正確設置道具,在你的構造函數,即結合您的handleClick功能:

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