2017-10-04 83 views
0

我是React的新手,很難完成Thunk。我讀了幾個問題,也指導,但我無法正確理解它。ReactJS - Thunk - Dispatch 2個事件同步一個接一個不能正常工作

我知道我必須連接,但我都失去了。請幫忙。

單派遣工作正常,但雙派遣根本不起作用。沒有記錄被打印。

handleSubmit(event) 
{ 
    event.preventDefault(); 
    this.isLoading = true; 

    // TWO EVENTS needed, first to add new player and then set as bowler 
    if (this.state.showAddBowlerTextfield) { 

     utilPostJSON(jsonURL + 'add-player.php', { 
      name: this.state.bowlerName, 
      matchId: this.currState.matchId, 
      inningsId: this.currState.inningsId, 
      teamId: this.currState.teamBowling.id, 
      isBowler: true 
     }) 
      .then((response) => { 
       console.log('Success', response); 

       this.setState({ 
        bowlerId: response.data.id, 
        bowlerName: response.data.name, 
       }); 

       this.dispatchAddPlayerAndAddBowler(); 
      }) 
      .catch((error) => { 
       console.error('Error', error); 
      }); 

     return 
    } 


    // This needs only one dispatch 
    const {store} = this.context; 
    this.currState = store.getState(); 

    store.dispatch({ 
     type: constants.NEW_BOWLER, 
     payload: this.state 
    }); 

    this.props.parentClose(); 
} 

//This function sends two dispatches 
dispatchAddPlayerAndAddBowler() 
{ 
    console.log('dispatchAddPlayerAndAddBowler'); 

    return (dispatch, getState) => { 
     const {store} = this.context; 
     console.log('Store', store); 

     store.dispatch({ 
      type: constants.NEW_PLAYER_BOWLER, 
      payload: this.state 
     }); 
     store.dispatch({ 
      type: constants.NEW_BOWLER, 
      payload: this.state 
     }); 
    } 
} 

日誌的輸出是:

Success {data: {…}, status: 200, statusText: "OK", headers: {…}, config: {…}, …} 
dispatchAddPlayerAndAddBowler 

回答

0

您正在使用的thunk錯誤。嘗試重構dispatchAddPlayerAndAddBowler

dispatchAddPlayerAndAddBowler() { 
    console.log('dispatchAddPlayerAndAddBowler'); 

    return (dispatch, getState) => { 
    // Wrong: const {store} = this.context; 
    // you don't need to do this dispatch is already there in the first parameter 

    dispatch({ 
     type: constants.NEW_PLAYER_BOWLER, 
     payload: this.state 
    }); 

    dispatch({ 
     type: constants.NEW_BOWLER, 
     payload: this.state 
    }); 
    } 
} 

而且你應該使用connectmapDispatchToPropshandleSubmit

+0

我不明白'connect'和'mapDispatchToProps'能否請你告訴我。 '函數mapDispatchToProps(調度){' 返回{ onHandleSubmit:(this.state)=> { 調度({ 類型:constants.NEW_PLAYER_BOWLER, 有效載荷:this.state }) } } } ' – Sallu

+0

您是否瀏覽過[docs](http://redux.js.org/docs/basics/UsageWithReact.html)?一旦你使用'connect',你應該使用'this.props.onHandleSubmit'在你的道具中獲得'onHandleSubmit',並且應該通過調用'this.props.onHandleSubmit(this.state)在'handleSubmit'實例方法的最後一位調用它)'。你也不應該在你的處理程序中使用'this.state',只是'onHandleSubmit:state => {dispatch({type:constants.NEW_PLAYER_BOWLER,payload:state})}' – excalliburbd

+0

抱歉,遲到了。我必須閱讀並嘗試文檔。非常感謝您寶貴的時間。 – Sallu

相關問題