反应redux嵌套调度未调用

时间:2017-06-02 09:12:56

标签: react-native redux redux-thunk

我正在使用redux with react native,我需要重复使用我的行为

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}))
  }
}

问题是获取帖子调度永远不会发生,因为。

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

您应该dispatch(fetchPosts()),并且可以在同一dispatch({type: LOGIN_SUCCESS, payload: response}回调中的then之后直接调用它,或者将其保留在第二个then回调中,它们都可以:

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}))
  }
}

答案 1 :(得分:0)

代码无效的主要原因是因为fetchPosts没有返回promise。请尝试以下代码:

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}))
  }
}