【问题标题】:Action Creator not awaiting动作创建者不等待
【发布时间】:2019-02-03 09:39:30
【问题描述】:

我在我的应用程序中使用占位符 json api 来获取一些帖子和他们的用户。但是,用户重复了 ID,并且这些 ID 被多次获取。所以我尝试使用以下代码仅获取唯一 ID。但是,当我在控制台记录 getState().posts 进行调试时,它显示一个空数组,因为 api 是稍后调用。

我不明白为什么“等待”不起作用..

另外,fetchUser 永远不会被调用,我不明白为什么..

我是 redux 的新手,如果这是一个愚蠢的问题,我很抱歉 这是我的代码

import _ from 'lodash' ;

export const fetchEvery = () => async (dispatch, getState) => {
console.log("Before") ;
await dispatch(fetchData()) ;
console.log("After" , getState()) ;
const ids = _.uniq(_.map(getState().posts, 'userId')) ;
console.log(ids) ;
ids.forEach( id => dispatch(fetchUser(id))) ;
} ;

export const fetchData = () => dispatch => {
    let resp = {} ;

    fetch('http://jsonplaceholder.typicode.com/posts/')
    .then( res => {
            if ( res.ok )
              return res.json() ;
            else 
              throw Error(res.statusText)
          } )
    .then( res => {
            console.log(res) ;
            resp = res ;
            dispatch( {
                    type : 'FETCH_DATA' ,
                    payload : resp  
                }) ;
                    } )
    .catch( err => console.log(err) ) ;

} ;

export const fetchUser = (id) => (dispatch) => {
fetch('http://jsonplaceholder.typicode.com/users/' + id )
.then( res => {
            if ( res.ok )
              return res.json() ;
            else 
              throw Error(res.statusText)
          } )
    .then( res => {
            console.log(res) ;
            dispatch( {
                    type : 'FETCH_USER' ,
                    payload : res  
                }) ;
                    } )
    .catch( err => console.log(err) ) ;

} ;

【问题讨论】:

    标签: javascript reactjs redux react-redux redux-thunk


    【解决方案1】:

    在您的获取方法中return fetch。目前他们没有返回任何东西 - 所以没有承诺 - 因此您在顶层的 await 正在立即解决,因为没有对 wait 的承诺。

    【讨论】:

      猜你喜欢
      • 2019-03-20
      • 2020-11-21
      • 1970-01-01
      • 2019-10-31
      • 2017-12-12
      • 1970-01-01
      • 2019-11-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多