为什么有时无法调用 fetch API?

问题描述 投票:0回答:1

在组件的构造函数类中,我对数据库进行 fetch 调用以获取一些数据。这是我的构造函数:

    constructor(props) {
    super(props)



    if (props.auth === false) {
        props.history.push("/")
    }

    //clearing reduce expenser before filling it up from the database to avoid duplicate data
    this.props.dispatch(resetExpenseReducer())

    //calling api to get all the expenses
    const url = "http://localhost:8080/getExpenses?email=" + encodeURIComponent(props.email)
    let h = new Headers({
        "Authorization": "Bearer " + props.token
    })

    let req = new Request(url, {
        headers: h
    })

    fetch(req).then((response, error) => {

        response.json().then((data, error) => {

            //filling the expenses in the reducer one by one
            for (let i = 0; i < data.length; i++) {

                this.props.dispatch(addExpense({ description: data[i].description, note: data[i].note, amount: parseInt(data[i].amount), createdAt: parseInt(data[i].createdAt), id: data[i].id }))

            }

        }).catch((error)=>{
            console.log(error)
        })
    }).catch((error)=>{
        console.log(error)
    })

}

我的数据库更新后(从另一个反应组件)重定向到此组件。如您所见,我首先清除我的 redux 存储。然后,使用 fetch API,我从数据库中获取所有数据并将其添加到 redux 存储中。这只是有时有效!

它连续工作大约 6-7 次,然后在下一次重定向到该组件时,redux 存储被清除,但没有添加数据。经过一些测试,我意识到根本没有调用 fetch API,但是代码执行到了调用的上方。我必须刷新页面才能再次开始工作。

请告诉我您需要的任何其他信息。

reactjs redux react-redux fetch-api
1个回答
0
投票

恐怕你的代码有点反模式。如果你想使用 redux,那么你应该在另一个文件中定义操作调度程序,并且 redux 存储数据应该在另一个文件中进行,而不是在组件构造函数中。

如果在获取完成之前卸载组件或在获取操作分派之后完成重置控制器分派,您将无法找到原因。我认为你的代码包含太多错误的地方。我建议您也检查生命周期功能。

© www.soinside.com 2019 - 2024. All rights reserved.