【发布时间】:2021-01-24 07:05:11
【问题描述】:
我正在创建我的第一个 ReactJS 前端应用程序,但遇到了问题。当我尝试用这个调用我的 setState 函数(或任何其他函数)时。在 if 块内之前,我得到了错误。
未处理的拒绝 (TypeError):无法读取属性“setState”的 未定义
当我调用 didComponentMount() 中的函数时,一切都很好,所以我认为问题出在 if 块上。我已经针对不同的问题尝试了几种解决方案,但没有一个有 if 块,所以它对我不起作用。
引发错误的函数:
getFilteredTrades() {
if(document.getElementById("switch").checked){
fetch("http://localhost:8080/trades/filter?plaform=NintendoSwitch").then(rse => rse.json()).then(
result => {
this.setState({trades: result});
}
)
} else if (document.getElementById("playstation").checked) {
fetch("http://localhost:8080/trades/filter?platform=PlayStation").then(rse => rse.json()).then(
result => {
this.setState({trades: result});
}
)
} else if (document.getElementById("xbox").checked) {
fetch("http://localhost:8080/trades/filter?platform=XBox").then(rse => rse.json()).then(
result => {
this.setState({trades: result});
}
)
} else if (document.getElementById("pc").checked) {
fetch("http://localhost:8080/trades/filter?platform=PC").then(rse => rse.json()).then(
result => {
this.setState({trades: result});
}
)
} else {
alert("No filter is selected, so all trades will be displayed.")
this.getAllTrades();
}
}
setState 和 getAllTrades 都会在这里抛出错误。
getAllTrades():
getAllTrades() {
fetch("http://localhost:8080/trades/all").then(rse => rse.json()).then(
result => {
this.setState({trades: result});
}
)
}
构造函数:
constructor(props){
super(props);
this.state = {
trades: []
}
}
didComponentMount,其中 getAllTrades 有效:
componentDidMount() {
this.getAllTrades();
}
有人知道这个问题的解决方案吗?提前致谢。
【问题讨论】:
标签: javascript reactjs this webstorm setstate