[英]React setState odd behaviour
React的新手,在以下代碼中,我通過父級在兩個組件之間傳遞數據。 流程是從Search
到父App
再到另一個子Sidebar
。 我能夠分別從Search to App和App到Sidebar發送到同一位置,但是由於某種原因, setState
的行為不符合預期,因此該鏈接觸發了刷新<Search updateMenu={this.handleSearchResult} />
如您所見下面的console.log
代碼注釋:
import React, { Component } from 'react';
import './App.css';
import Search from './Search';
import Sidebar from './Sidebar';
class App extends Component {
constructor() {
super()
this.state = {
menu: []
}
}
handleSearchResult = (array) => {
// always the correct value
console.log('in ', array);
this.setState( {menu: menuList})
// 1st call : empty
// 2nd call : previous value not showing on 1st call + new value as expected
// does not trigger <Sidebar list={this.state.menu}/>
console.log('out', this.state.menu);
}
render() {
return (
<div className="App">
// not refreshing
<Search updateMenu={this.handleSearchResult} />
<Sidebar list={this.state.menu}/>
</div>
);
}
}
export default App;
記錄this.setState()
。 不是那么直接。 this.setState()
是異步的。
這是有關Medium的參考 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.