我有一个组件,该组件是另一个组件的子组件,该组件在安装时称为getData()函数。在对方法setState的databse调用进行了一些查询之后,此函数无效,但是此调用不起作用,因为它不会更改load的值并且不会执行回调。
该组件的代码为:
<!DOCTYPE html>
<html>
<head>
<meta charset="US-ASCII">
<title>Calculator</title>
</head>
<body>
<form action="Converter" method="post" name="frm">
Amount:
<input name="amount" type="text" />
Rate:
<input name="conversionRate" type="text" />
<input type="submit" value="Convert!" />
</form>
</body>
</html>
这些代码何时被期望写入console.log:
如何查看属于该说明的日志未执行:
import React, {Component} from "react";
import {Determinator, MultiLang} from "react-multi-language";
import { getDataFromServer } from "./Functions";
import {GAME_STATS_BY_TEAM, TEAM_COMPETITION_STATS} from "../FEBCOM/Querys";
class TeamTableStandardStats extends Component {
constructor(props){
super();
this.props = props;
this.state = {
loaded: false,
lang: this.props.isFEB ? "es" : "en"
};
}
componentDidMount(){
this.getData();
}
async getData(){
let params = [
{"###id_team_club###": this.props.id_team},
{"###id_competition###": this.props.id_competition}
];
let team_games_stats = {};
let team_comp_stats = {};
if (this.props.isFEB){
team_games_stats = await getDataFromServer(process.env.URL_FEB_API, GAME_STATS_BY_TEAM, params);
team_comp_stats = await getDataFromServer(process.env.URL_FEB_API, TEAM_COMPETITION_STATS, params);
}else{
team_games_stats = await getDataFromServer(process.env.URL_FIBA_API, GAME_STATS_BY_TEAM, params);
team_comp_stats = await getDataFromServer(process.env.URL_FIBA_API, TEAM_COMPETITION_STATS, params);
}
console.log("getData() => Before setState");
this.setState = ({
loaded: true,
// team_games_stats: team_games_stats.data.game_stats_by_team,
// team_comp_stats: team_comp_stats.data.team_comp_stats
}, () => {
console.log("loaded: " + this.state.loaded);
});
console.log("getData() => After setState");
}
render(){
return(
<div>
<span>loaded: {this.state.loaded ? "YES" : "NO"}</span>
{
(this.state.loaded) ?
<div>
<h1>Tabla - {this.props.isFEB ? "Es FEB" : "Es FIBA"}</h1>
<span>id_team: {this.props.id_team} - id_competition: {this.props.id_competition}</span>
<span>Resumen: {this.state.team_comp_stats.length}</span>
</div>
:
<h5>
<Determinator>
{{
es: "Cargando datos ...",
en: "Loading data ..."
}}
</Determinator>
</h5>
}
<MultiLang lang = {this.state.lang} />
</div>
)
}
}
module.exports.TeamTableStandardStats = TeamTableStandardStats;
如何加载为假,您可以在视图中看到这一点:
所以,我不知道为什么不执行setState方法。
我在做什么错?
答案 0 :(得分:4)
从外观上讲,您根本没有调用 setState
,而是在设置
this.setState = ({ ... })
此行分配了setState
的值,这是完全错误的,setState
是一个函数,您需要调用该函数来更新状态,即
this.setState({
...
})
答案 1 :(得分:1)
setState
是一种应调用的方法,而不是为其分配新值。