2017-06-02 45 views
0

我使用終極版與原生的反應,我需要重新用我的行動反應過來終極版嵌套調度不叫

const fetchPosts =() => { 

    return (dispatch) => { 

    Api.get('/posts') 
     .then(response => dispatch({type: FETCH_POSTS_SUCCESS, payload: response})) 
     .catch(err => dispatch({type: FETCH_POSTS_FAIL, payload: err})) 
    } 
} 

我想在登錄

const login = ({username, password}) => { 

    return (dispatch) => { 

    Api.post('/auth', {username, password}) 
     .then(response => dispatch({type: LOGIN_SUCCESS, payload: response}) 
     .then(() => fetchPosts()) 
     .catch(err => dispatch({type: LOGIN_FAIL, payload: err})) 
    } 
} 

問題後總是取帖子是抓取帖子派遣不會發生的原因。

有什麼建議嗎?

回答

0

代碼不工作的主要原因是因爲fetchPosts沒有返回承諾。試試下面的代碼:

const fetchPosts = (dispatch) => { 
 
    return Api.get('/posts') 
 
     .then(response => dispatch({type: FETCH_POSTS_SUCCESS, payload: response})) 
 
     .catch(err => dispatch({type: FETCH_POSTS_FAIL, payload: err})) 
 
} 
 

 
const login = ({username, password}) => { 
 
    return (dispatch) => { 
 
    Api.post('/auth', {username, password}) 
 
     .then(response => dispatch({type: LOGIN_SUCCESS, payload: response}) 
 
     .then(() => fetchPosts(dispatch)) 
 
     .catch(err => dispatch({type: LOGIN_FAIL, payload: err})) 
 
    } 
 
}

+0

遺憾沒派遣登錄操作錯誤(我做了糾正我的代碼) –

+0

,我想重用fetchPosts()其他地方 –

+0

嘗試編輯答案。 –

1

你應該dispatch(fetchPosts()),你可以直接在同一then回調稱之爲dispatch({type: LOGIN_SUCCESS, payload: response}後,或保持在第二then回調,它們都是OK:

const login = ({username, password}) => { 

    return (dispatch) => { 

    Api.post('/auth', {username, password}) 
     .then(response => { 
     dispatch({type: LOGIN_SUCCESS, payload: response} 
     dispatch(fetchPosts()) 
     }) 
     .catch(err => dispatch({type: LOGIN_FAIL, payload: err})) 
    } 
}