在我的组件的构造函数类中,我对数据库进行了一次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)
})
}在我的数据库更新后,我重定向到这个组件(从另一个react组件)。如你所见,我首先清空了我的redux商店。然后,使用fetch API,我从数据库中获取所有数据,并将其添加到redux存储中。这只会在某些时候起作用!
它连续工作大约6-7次,然后在下一次重定向到此组件时,redux存储将被清除,但不会添加任何数据。经过一些测试后,我意识到fetch API根本没有被调用,但是代码的执行恰好在调用之上。我必须刷新页面才能重新开始工作。
如果您需要任何其他信息,请告诉我。
发布于 2021-07-03 02:25:01
恐怕您的代码有点反模式。如果你想使用redux,那么你应该在另一个文件中定义动作分派器,并且redux存储数据应该在另一个文件中进行,而不是在组件构造函数中。
如果在fetch完成之前卸载组件,或者在fetch操作调度之后完成重置控制器调度,您将无法找到原因。我认为你的代码包含了太多的bug。我建议你也检查一下生命周期的功能。
https://stackoverflow.com/questions/68229576
复制相似问题