无法从 React Native 应用程序内的 reducer 中的操作获取有效负载?

Unable to get payload from action in reducer inside react native app?

我正在尝试从 api 获得 json 响应并成功获取数据,但是当我使用 redux-thunk 在另一个动作中调用一个动作时,我的数据在减速器。 我需要 "data" 属性 中的数据,在我的 reducer get in component 中。检查下面的代码。

这是我的行动

import { GET_REPORT, GET_DATA_SUCCESS } from './types';

export const getData = (text) => {
    
    return (dispatch) => {
        dispatch ({ type: GET_REPORT})
        fetch('http://api.openweathermap.org/data/2.5/forecast?q='+text+'&cnt=1&units=metric&APPID={key}')
            .then(response => response.json())
            .then(data => getDataSuccess(dispatch, data.list[0]))
            .catch((error) => console.log(error));
    };
};

const getDataSuccess = (dispatch, data) => {
    //console.log(data);
    dispatch({
        type: GET_DATA_SUCCESS,
        payload: data
    });
}

这是我的减速器

import { GET_REPORT } from'../actions/types';

const INITIAL_STATE = {
    data: '',
}

export default (state = INITIAL_STATE, action) => {
    switch(action.type){
        case GET_REPORT:
            console.log(action.payload); // getting undefined
            return {...state, data: action.payload};
        default:
            return state;
    }
}

我需要 "data" 中的数据 属性 get in component.

操作 dispatch ({ type: GET_REPORT}) 不包含负载,因此 undefined。您需要制作 reducer 来处理 action GET_DATA_SUCCESS 或修改现有的 reducer。

为简化起见,dispatch({ type: GET_DATA_SUCCESS, payload: data }); 包含有效载荷,而 dispatch ({ type: GET_REPORT}) 不包含

通过为 GET_DATA_SUCCESS 添加新的 switch case 并从 getDataSuccess 获取有效负载并从 GET_REPORT case 中删除有效负载来解决它。 现在开关盒看起来像这样

switch(action.type){
        case GET_REPORT:
            return {...state};
        case GET_DATA_SUCCESS:
            console.log(action.payload);
            return{...state, data: action.payload}
        default:
            return state;
}

您的减速器

中缺少 GET_DATA_SUCCESS