gpt4 book ai didi

javascript - 未处理的拒绝(TypeError): this. setState 不是函数

转载 作者:行者123 更新时间:2023-12-02 23:23:51 24 4
gpt4 key购买 nike

当我执行点击事件时,setState 无法在 fetch 中工作。

buttonClick = (event) => {
let category = event.target.id;
let url = this.state.urls[category];
this.setState = ({
planets: [],
starships: [],
vehicles: [],
people: [],
films: []
});
fetch(url)
.then(resp => resp.json())
.then(
data => this.setState({ category: data }) //error: Uncaught (in promise) TypeError: this.setState is not a function
);
};

希望修复这个错误

最佳答案

Problem

这里的问题是您将 setStatefunction 重写为 object

当你写的时候

    this.setState = ({
planets: [],
starships: [],
vehicles: [],
people: [],
films: []
});

然后 this.setState 不再是一个函数,稍后你尝试调用它,所以错误是预料之中的,this.setState 不是一个函数。

<小时/>

Solution

您所要做的就是不要将数据分配给setState,只需在函数调用中传递数据,如

  this.setState({
planets: [],
starships: [],
vehicles: [],
people: [],
films: []
});

您在fetchthen中调用setState将起作用

关于javascript - 未处理的拒绝(TypeError): this. setState 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56826039/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com