3 回答

TA貢獻1852條經驗 獲得超7個贊
如果您在任何方法中使用this.state,請使用箭頭函數或綁定您的操作。
箭頭函數:
onSubmitUpdateState = (newNote) => {
const oldState = [...this.state.notes]
// Problem 2)
this.setState({notes: [...oldState, newNote]});
}
綁定方法: 創建構造函數并在構造函數中添加這一行
this.onSubmitUpdateState = this.onSubmitUpdateState.bind(this)
沒有構造函數
<Create updateState={this.onSubmitUpdateState.bind(this)}/>

TA貢獻1827條經驗 獲得超4個贊
在 Javascript 中,類方法在默認情況下不受限制,這個 SO 答案討論了為什么會這樣?
如果您不使用箭頭函數,請確保bind()您的事件處理程序能夠訪問this.
<Create
updateState={this.onSubmitUpdateState.bind(this)} // pass a binded handler
/>

TA貢獻1784條經驗 獲得超8個贊
嘗試這樣做
class App extends Component{
state = {
notes: []
}
componentDidMount(){
fetch('http://localhost:3001/notes')
.then(resp => resp.json())
.then(data => this.setState({notes: data}))
}
onSubmitUpdateState = (newNote) => { //change to arrow function//
const oldState = [...this.state.notes]
// Problem 2)
this.setState({notes: [...oldState, newNote]});
}
render(){
return(
<div className="App">
<Notes notes={this.state.notes}/>
<Create updateState={this.onSubmitUpdateState}/>
</div>
)
}
}
export default App;
箭頭語法this為您處理綁定。或者您可以bind在構造函數中使用該函數。`
基本上箭頭函數this在調用時會保留上下文
添加回答
舉報