redux 操作函数未正确执行 - 展示“可能未处理的承诺拒绝"

此时我遇到了一个非常奇怪的问题,我不知道如何准确描述它,所以我将尝试首先向您展示所有相关的数据:

I have a really strange problem facing at this point and I dont know precisely how to describe it so I will try to first show you all the data that is relevant:

这是函数的代码:

export const fetchPigeons = () => {
    return async (dispatch, getState) => {
        const PersonalId = getState().auth.userId;
        const response = await fetch(`https://pigeonbuddy-*****.firebaseio.com/users/${PersonalId}/pigeons.json`);
        const resData = await response.json();
        const jsonValue = await fetch('https://geolocation-db.com/json/85****90-4601-11eb-9067-21b51bc8dee3').then((response) => response.json()).then((json) => {return json.country_code});
        console.log("123", jsonValue); //Logging of the Location!

        console.log(resData);
        const loadedPigeons = []; //create new empty array
        for (var key in resData){ //load up new created array with pigeons from server
            console.log("VOGEL DETECTED");
            switch(resData[key].id){
                case 1:
                    var tempPigeon = ALLPIGEONS[0];
                    tempPigeon.key = key;
                    loadedPigeons.push(tempPigeon);
                    continue;
                case 2:
                    var tempPigeon = ALLPIGEONS[1];
                    tempPigeon.key = key;
                    loadedPigeons.push(tempPigeon);
                    continue;
                case 3: 
                    var tempPigeon = ALLPIGEONS[2];
                    tempPigeon.key = key;
                    loadedPigeons.push(tempPigeon);
                    continue;
                case 4: 
                    var tempPigeon = ALLPIGEONS[3];
                    tempPigeon.key = key;
                    loadedPigeons.push(tempPigeon);
                    continue;
                case 5:
                    var tempPigeon = ALLPIGEONS[4];
                    tempPigeon.key = key;
                    loadedPigeons.push(tempPigeon);
                    continue;
                case 6:
                    var tempPigeon = ALLPIGEONS[5];
                    tempPigeon.key = key;
                    loadedPigeons.push(tempPigeon);
                    continue;
                default:
                    console.log("Not working");
            }
        };
        console.log("hier sind meine vögel: ", loadedPigeons);
        dispatch({type: SET_PIGEONS, pigeons: loadedPigeons, location: jsonValue})
    }
};

我在这里所做的基本上是搜索用户是否有鸽子,如果是这样,则通过 id 将它们存储在本地.

What Im doing here is basicly searching if the user has pigeons and if thats the case, store them localy by id.

我通过调用我的其他文档中的操作来做到这一点:

Im doing this by calling the action in my other documents like that:

import * as authActions from '../store/actions/auth';
import {useDispatch} from 'react-redux';
//some other code
useDispatch(pigeonActions.fetchPigeons());

问题是两个 console.log() 命令都不起作用,JS 根本没有注意到我在等待响应,终端没有显示任何内容,我的意思是这两个日志:

The problem is that both console.log() orders are not working, JS is simply not even noticing me waiting for a response, the terminal doesnt show up anything, I mean this both logs:

console.log("123", jsonValue); //Logging of the Location!
console.log(resData);

我已经检查了获取命令是否有问题,但事实并非如此,我至少从 firebase 获取值,似乎在我从 geolocation-db 获取数据后,整个函数停止执行而没有任何错误,只是什么都不做.

I already checked if the fetch orders are maybe buggy but thats not the case, I definetly get values from firebase at least, it seems like after I fetch data from geolocation-db the whole function stops to execute without any error and just does nothing anymore.

世博会传达给我的唯一一个我无法真正使用的消息是这里:

The only message expo delivers me which I cant really work with is this here:

此时我真的很无助,不知道该怎么办了.关于警告的唯一事情是它多次引用 192.168.178.43:19001 即使在我的浏览器窗口中也告诉我我在 192.168.178.43:19000 上运行,你可以在这里看到它:

Im feeling really helpless at this point and dont know what to do anymore. The only thing about the warning is that its referencing multiple times to 192.168.178.43:19001 even tho in my browser window expo tells me im running on 192.168.178.43:19000 and you can see it here:

如有必要,我会尽力为您提供任何信息和代码示例,此时我不知道该怎么做.任何信息都被appriciated!

I will try to provide you with any infos and code samples if necessary, at this point I dont know anymore what to do. Any info is appriciated!

推荐答案

您没有正确使用 useDispatch 挂钩.您需要调用不带参数的 useDispatch() 才能访问 dispatch 函数.然后您使用该函数来调度操作.

You are not using the useDispatch hook correctly. You need to call useDispatch() with no arguments in order to access to the dispatch function. Then you use that function to dispatch actions.

const dispatch = useDispatch();

const load = () => {
  dispatch(pigeonActions.fetchPigeons());
}

如果您想自动调度操作,那么您可以使用 useEffect 挂钩.

If you want to dispatch the action automatically then you would do that with a useEffect hook.

const dispatch = useDispatch();

useEffect(() => {
  dispatch(pigeonActions.fetchPigeons());
}, []);


可能的未处理承诺拒绝";警告您,如果您的 fetchPigeons 操作中的 fetch 请求失败,您将遇到运行时错误.你想catch 这些错误.当在异步操作创建器中捕获错误时,通常会分派失败操作.


The "possible unhandled promise rejection" is warning you that you will have runtime errors if the fetch requests in your fetchPigeons action fail. You want to catch these errors. It is typical to dispatch a failure action when errors are caught within an async action creator.

export const fetchPigeons = () => {
  return async (dispatch, getState) => {
    try {
      /**... your code ...**/
      dispatch({type: SET_PIGEONS, pigeons: loadedPigeons, location: jsonValue})
    } catch (error) {
      dispatch({type: FETCH_PIGEONS_ERROR, error: error?.message})
    }
  }
};

我建议使用 createAsyncThunk 函数官方 Redux 工具包,它自动分派pending"、fulfilled"和rejected";行动.

I recommend using the createAsyncThunk function from the official Redux Toolkit which automatically dispatches "pending", "fulfilled", and "rejected" actions.

您对响应的处理可以主要清理,但我不明白这个 ALLPIGEONS 变量来自哪里?这是您当前的逻辑,行数要少得多.

Your handling of the response can be cleaned up majorly, but I'm not understanding where this ALLPIGEONS variable comes from? This is your current logic in a lot less lines.

const loadedPigeons = Object.keys(resData).map((key) => {
  const id = resData[key].id;
  return {
    ...ALLPIGEONS[id - 1],
    key
  };
});

但我真的怀疑你的意图是忽略响应中的所有内容,除了 key.

But I really doubt that your intention is to disregard everything from the response except the key.

相关文章