2017-10-25 22 views
-2

私は小さな反応アプリを構築しています。私は状態が更新されないという奇妙な状況があります。React - stateは更新されません

class App extends Component { 

constructor() { 
    super(); 

    this.state = { 
    locale: 'de', 
    countryList: [], 
    fetchInProgress: true, 
    serverError: {}, 
    person: { 
     salutation: '', 
     firstName: '', 
     lastName: '', 
     birthDate: '', 
     nationality: '', 
     address: '', 
     zipCode: '', 
     city: '', 
     country: '', 
     mobileNumber: '', 
     email: '', 
     correspondanceLanguage: '', 
    } 
    }; 
} 

componentDidMount() { 
    this.setState({ 
    fetchInProgress: false 
    }),()=>console.log('State updated', this.state) 
} 

}

私も他のアプローチを使用してみました::ここでは一例である

componentDidMount() { 
    const temp = {...this.state}; 
    temp.fetchInProgress = false; 
    this.setState(temp),()=>console.log('State updated', this.state) 
} 

componentDidMount() { 
    const temp = {...this.state}; 
    temp['fetchInProgress'] = false; 
    this.setState(temp),()=>console.log('State updated', this.state) 
} 

をしかし、状態更新されることはありません。どんな助け?

答えて

1

すべてのアプローチで構文エラーがあります。 updaterのいずれかの関数またはオブジェクト及び場所callbackの関数であることができる

setState(updater, callback) 

setState()は、以下のフォーマットを有することに留意されたいです。


あなたの最初のアプローチを皮切り:

this.setState({ 
    fetchInProgress: false 
}),()=>console.log('State updated', this.state) 

は、代わりに次のようになります。

this.setState({ 
    fetchInProgress: false 
},()=>console.log('State updated', this.state)) 

、再び、あなたはsetState()部分を取得するまで、他のコードが正しいです。

this.setState(temp),()=>console.log('State updated', this.state) 

は、代わりに次のようになります。

this.setState(temp,()=>console.log('State updated', this.state)) 
+0

はあなたにクリスをありがとう! 4つの目は常に2より良いです:) –

関連する問題