[英]React: undefined the state of `this.setState` instantly
為什么我越來越不確定,如果我叫console log
后this.setState
在相同的狀態componentWillMount
這個例子將說明問題
constructor(props){
super(props);
this.state = {
total: 100,
length: null,
number: null,
}
}
componentWillMount(){
let JSONFetchedNumber = 30.20;
this.setState({length: JSONFetchedNumber});
console.log(this.state.length);// getting Null response
let collect = this.state.total/this.state.length;
let result = collect.toFixed(0)/1+1;
this.setState({number: result});// This won't work cus length state in undefined
}
render() {
console.log(this.state.length);// getting 30.20 Successfully
為什么我不能在componentWillMount
立即使用this.setState
的狀態? 它僅適用於渲染
我試圖使用componentDidMount
它不會起作用。 僅在渲染工作中,這里的問題是我無法在渲染中使用this.state
this.setState是一個異步函數,需要一些時間才能完成。 如果要記錄狀態,則精確的方法是將其記錄在this.setState的回調中。 這應該工作,
this.setState({length: JSONFetchedNumber}, ()=> console.log(this.state.length););
this.setState是一個異步函數。 您正在嘗試訪問它,然后再更新狀態。 因此,無論您要對狀態進行何種操作,都可以在回調函數中進行操作。
this.setState({length:JSONFetchedNumber},()=>{
//Your code which is using state
console.log(this.state)
})
您不應在JavaScript中將length用作關鍵字,我很確定這是您的錯誤。
var.length
是javascript中的工具,用於獲取變量的實際長度,那里一定有沖突。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.