【问题标题】:How to fetch data from my own api using redux?如何使用 redux 从我自己的 api 中获取数据?
【发布时间】:2021-02-06 08:11:58
【问题描述】:

我正在尝试使用 redux 从我自己的 api 中获取数据,但我得到一个空对象并且不知道为什么会发生这种情况。 API 是使用 express.js 和 MongoDB 编写的。当我使用邮递员时它可以工作。我也使用 redux-thunk。有人可以解释一下,怎么了? 任何帮助表示赞赏!

这是我的代码:

这是我的行动:

export const fetchClientsSuccess = (clients: any): FetchDataAction => {
    return {
        type: CLIENTS_FETCH_DATA_SUCCESS,
        payload: clients
    }
}


export const clientsFetchData = (url: string) => {
    return (dispatch: any) => {
        fetch(url)
            .then(response => {
                if(!response.ok){
                    throw new Error(response.statusText);
                }
                
                return response;
            })
            .then(response => {
                response.json();
            })
            .then(clients => {
                dispatch(fetchClientsSuccess(clients))
            })
    }
};

这里是减速器:

const initialState:InitialStateType = {
    entries: [],
    loading: false,
};


export const clientsFetchReducer = (state = initialState, action: any) => {
    switch(action.type){
        case CLIENTS_FETCH_DATA_SUCCESS: 
            return {
                ...state,
                entries: [...action.payload]
            };
        default:
            return state;
    }
}

最后是容器:

import * as React from "react";
import { connect } from 'react-redux';

import { App } from '../components/App/App';
import { clientsFetchData } from '../actions/clients';
import { AppContainerComponentProps, AppContainerState } from './AppContainer.interface';

class AppContainerClass extends React.Component<AppContainerComponentProps, AppContainerState>{
    componentDidMount(){
        this.props.fetchData('/api/clients')
    }

    render(){
        const {clients} = this.props;
        return(
            <App clients={clients}
            />
        );
    }
}


const mapDispatchToProps = (dispatch: any) => {
    return {
        fetchData: (url: string) => dispatch(clientsFetchData(url))

    }
}
const mapStateToProps = (state: any) =>{ 
    return {
        clients: state.entries,
    };
}

export const AppContainer = connect(mapStateToProps, mapDispatchToProps)(AppContainerClass);

【问题讨论】:

  • 尝试将链接的catch 添加到您的clientsFetchData,函数可能会引发错误。有时如果您没有设置正确的contentType 并尝试将其转换为 json 它会失败,这可能是一个原因,
  • @Anuja 我添加了一个 catch,但它也不会抛出任何错误
  • 这样的异步请求必须有asyncawait否则你不会响应,因为功能不会等待。
  • 我添加了,没有任何变化
  • @arisha 我认为您需要逐步调试,1. 检查 api 调用是否正在通过并返回数据 2. 使用 redux-dev tools 检查是否正在更新 redux 状态 2. 检查如果它被返回到连接的组件

标签: reactjs typescript redux redux-thunk


【解决方案1】:

我觉得您的请求将发送到 /api/clients,但没有附加任何 baseURL。

您能否确认fetch实际上是在调用像-http://localhost:4000/api/clients这样的URL,而不仅仅是/api/clients...

您是否也可以尝试在您的fetch 调用中添加一个catch 块并在您的respose.json 中添加一个return 关键字,如下所示:


        fetch(url)
            .then(response => {
                if(!response.ok){
                    throw new Error(response.statusText);
                }
                
                return response;
            })
            .then(response => {
                return response.json(); //<--- add return here
            })
            .then(clients => {
                dispatch(fetchClientsSuccess(clients))
            })
            .catch(err=> console.log("ERROR",err); // <------ add this



【讨论】:

  • 感谢您的回答,我也尝试使用此 url,但没有任何改变,可能是 fetch 功能有问题。但我也没有收到任何错误
  • 你的nodejs服务器的url是什么??
  • localhost:4000/api/clients ,我按照这个 url 和 api 工作正常
  • 那么也许你在前端的fetch调用应该是调用http://localhost:4000/api/clients
  • 是的,我改变了它,现在它调用了这个 url,但我仍然没有得到任何东西..(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-06-15
  • 2014-03-24
  • 1970-01-01
  • 1970-01-01
  • 2021-09-27
  • 2022-01-20
  • 1970-01-01
相关资源
最近更新 更多