[英]Why am I getting a cannot read property props error for my function passed to a child?
所以我有一個按鈕來更新存儲在我的后端的數組,我需要這個按鈕來更新我前端的 state 與后端的新數組。 我正在傳遞一個 function ,它將父級的 state 更改為按鈕,但是當我嘗試調用該 function 時,無法使用 this.props.function()
我有另一個按鈕,它使用基本相同的代碼(除了這個我在另一個 function 中調用傳遞的 function ,我綁定到 onClick)並且工作得很好,所以我很困惑為什么這個不工作。
家長:
//within constructor
this.onUpdateRooms = this.onUpdateRooms.bind(this);
//function
onUpdateRooms(list) {
this.setState({roomList: list});
console.log(this.state.roomList);
}
//within render
<GenerateButton onUpdateRooms={this.onUpdateRooms}/>
按鈕
//within the class declaration
constructor (props) {
super(props)
}
onCreateNewRoom() {
const newRoomCode = GenerateRandomCode.TextCode(6).toUpperCase();
console.log(newRoomCode);
let temp;
fetch('/api/newRoom', {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({roomCode: newRoomCode})
})
.then(res => res.json())
.then(list => temp=list);
this.props.onUpdateRooms(temp);
}
//then i set the button's onClick={this.onCreateNewRoom}
我似乎無法弄清楚出了什么問題。 在過去的 2 個小時里,我一直在刪除和添加內容。 幫助將不勝感激:)
您還需要在onCreateNewRoom
上調用bind
constructor (props) {
super(props);
this.onCreateNewRoom = this.onCreateNewRoom.bind(this);
}
您還可以使用箭頭函數來避免重新綁定this
錯誤和此類錯誤:
onCreateNewRoom = () => {
因此onCreateNewRoom
this
內部將綁定到 class 而不是onClick
處理程序 function。
bind() 方法創建一個新的 function,當調用它時,它的 this 關鍵字設置為提供的值,在調用新的 ZC1C425268E68385D1AB5074C17A94F1 時,給定的 arguments 序列在任何提供的序列之前。
在構造函數中this
綁定到 class。 當您調用this.onCreateNewRoom.bind(this)
時,您正在將onCreateNewRoom
內部的this
設置為您作為第一個參數傳遞給bind
的值。 ( this
是綁定到 class 並包含props
的 this )。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.