2016-12-30 37 views
7

我有一個異步動作,這從REST API獲取數據陣營Redux的調度動作top = 10, skip = 0的初始狀態。在組分:後另一個動作

class List extends Component { 
    componentDidMount() {   
     this.list(); 
    } 

    nextPage() { 
     let top = this.props.list.top; 
     let skip = this.props.list.skip; 

     // After this 
     this.props.onSetSkip(skip + top); 

     // Here skip has previous value of 0. 
     this.list(); 
     // Here skip has new value of 10. 
    } 

    list() { 
     this.props.List(this.props.list.top, this.props.list.skip); 
    } 

    render() { 
     return (
      <div> 
       <table> ... </table> 
       <button onClick={this.nextPage.bind(this)}>Next</button> 
      </div> 
     ); 
    } 
} 

當按鈕接着在第一次點擊時,它採用異步動作的skip值沒有改變。 如何在同步後採取行動?

回答

0

感謝您的答覆,但我做了這種方式:

let top = this.props.list.top; 
let skip = this.props.list.skip; 
let newSkip = skip + top; 

this.props.onList(top, newSkip); 
this.props.onSetSkip(newSkip); 

首先我計算新skip和派遣這種新的價值的異步操作。然後我派遣syns行動,更新skip狀態。如果您正在使用redux thunk

3

而不是在同步動作後調度一個動作,你可以調用reducer的功能嗎?

所以它遵循這一流程:

同步行動呼籲 - >減速通話--->功能的情況下(減速)--->功能的情況下(減速)

代替通常的流動,這可能是爲你好:

同步行動呼籲 - >減速通話

按照本指南split the reducers up查看減速器是什麼情況。

如果您想分派的動作有副作用,那麼正確的方法是使用Thunk,然後您可以在動作後分派動作。

示例Thunks

export const setSkip = (skip) => { 
    return (dispatch, getState) => { 

     dispatch(someFunc()); 
     //Do someFunc first then this action, use getState() for currentState if you want 
     return { 
      type: 'LIST.SET_SKIP', 
      skip: skip 
     }; 
    } 
}; 
+0

感謝您的幫助。你能提供一些示例代碼嗎? (我是一個反應敏捷的人)。 –

+0

@DenisBednov如果你按照thunks指南,thunks應該爲你工作。 無論如何你都可以將你的減速器分解,就像我在指南中一樣,你會知道我在說什麼。 –

0

調度({類型: 'LIST.SUCCESS',數據:數據,跳過:同步動作後所需的值});

1

,您可以輕鬆地將它們結合起來。 這是一個讓動作創作者可以返回一個函數而不是一個動作的中間件。

如果您不需要鏈接動作創建者並只需要運行它們,那麼現在您的解決方案可能對您有用。

this.props.onList(top, newSkip); 
this.props.onSetSkip(newSkip); 

如果您需要鏈接(以同步方式調用它們)或從第一次調度動作的數據等,這就是我建議。

export function onList(data) { 
    return (dispatch) => { 
      dispatch(ONLIST_REQUEST()); 
    return (AsyncAPICall) 
    .then((response) => { 
     dispatch(ONLIST_SUCCESS(response.data)); 
    }) 
    .catch((err) => { 
     console.log(err); 
    }); 
    }; 
} 

export function setSkip(data) { 
     return (dispatch) => { 
       dispatch(SETSKIP_REQUEST()); 
     return (AsyncAPICall(data)) 
     .then((response) => { 
      dispatch(SETSKIP_SUCCESS(response.data)); 
     }) 
     .catch((err) => { 
      console.log(err); 
     }); 
     }; 
    } 

export function onListAndSetSkip(dataForOnList) { 
    return (dispatch) => { 
    dispatch(onList(dataForOnList)).then((dataAfterOnList) => { 
     dispatch(setSkip(dataAfterOnList)); 
    }); 
    }; 
} 
相關問題