2016-12-15 9 views
0

私は非同期呼び出しの概念を理解する上で問題に直面しました。状態の更新後に非同期関数を呼び出す方法は?

私の状態:sentence: { author: '', context: '', date: '' }

それから私はReduxの状態を更新する機能を持っている:

edit(author, date) { 
    let { sentence } = this.props; 
    this.props.updateAuthor(sentence, author); 
    this.props.updateDate(sentence, date) 
} 

これらの更新方法が異なるアクションであり、異なる減速を持っています。

は、更新された状態の属性の後、私はこれでサーバーにデータを送信したい:

function uploadToServer() { 
    this.props.upload(this.props.sentence); 
} 

私は更新が終了した後、アップロード機能を呼び出す方法に迷ってしまいました。

+0

は、あなたが何をすべき:あなたは2番目のパラメータでコールバックを呼び出すために必要があるのでsetStateは非同期です。 今のところ、あなたがリデューサーのみをアップデートしている場合、updateAuthorとupdateDateを使用してサーバーにリクエストすることなく、アップロードする前にレデューサーを待つ必要はありません。 – jmac

+0

実際には私の状態はこれよりずっと大きく、内部のオブジェクトはデータの配列が異なっていて、アップロードする前にサーバにIDとその配列のいくつかの属性を読み込み、各チャンクごとに異なるURL。 –

+0

ライフサイクルメソッドを使用することができます:* componentWillReceiveProps()*。接続された減速機が更新されるたびに、新しい小道具に関する情報が得られます。 – jmac

答えて

1

componentDidUpdateまたはcomponentWillReceivePropsライフサイクルメソッドを使用して、新しい小道具に変更が加えられているかどうかを確認してから、this.props.uploadを実行することもできます。

componentWillReceiveProps (newProps) { 
    // check if your state is updated with the attributes 
    // this function will get called when it's going to receive new props, 
    // in this case, when the redux store gets changed 
    // this.props will be the unchanged props, newProps will be the changed props 
    // then do this.props.upload() 
} 
+0

はい、ありがとうございます。これは、receivePropsで更新する方が良い方法です。私は前にそれを試していたが、小道具とnextPropsの比較で間違いを犯していた。 –

1

のようなものと同じ機能で、両方の更新プログラムを作成し、この関数にコールバックを渡す:

edit(author, date) { 
    const { sentence, updateAuthorAndDate } = this.props 
    updateAuthorAndDate(sentence, author, date, this.uploadToServer) 
} 

次にupdateAuthorAndDateに、更新が行われたときにだけ、コールバックを呼び出します。

updateAuthorAndDate(sentence, author, date, uploadToServer) { 
    // update the author 
    // update the date 
    // then call the callback when the updates are done: 
    uploadToServer() 
} 

setStateを使用する場合は注意してください(おそらくReduxを使用していない場合)。周りの他の方法は、最初のサーバに文をアップロードしてから応答が成功した解決の約束がある場合や状態を更新すること

this.setState({ ... }, /* called when the update is done */ uploadToServer) 
+0

こんにちは、本当に助けてくれてありがとう、実際に私は、生活を楽にしていたcomponentWillReciveProps –

関連する問題