我在Modalselector上具有_onchange函数,我需要从firebase数据库中获取一些东西。
1(如果我在getTeamOption(option(
中使用此此信息this.setState({TeamRequest: childComplete}
它不起作用。当我登录该状态时,似乎是空字符串。
2(如果我在getTeamOption(option(
中使用此此信息self.setState({TeamRequest: childComplete}, () => {});
log还不是空的,但是它登记相同的值,第一个。实际上,我只有在Onchange功能中才有这个问题。我在componentDidmount函数中使用几乎相同的代码作为另一个数据,而1(示例如我想要的。
constructor(props){
super(props);
this.state = {
Loaded: false,
Optionn:'',
LeagueOption: '',
TeamOption: '',
LeagueRequest: '',
TeamRequest: '',
TeamsToMapRequest: [],
LeaguesToMapRequest: []
}
}
GetTeamOption(option){
const self = this;
let index = 0;
let object = {};
let TeamsArr = [];
this.setState({LeagueOption: option.label}, function () {
const refTeam = firebase.database().ref('leagues/' + this.state.LeagueOption + '/');
refTeam.orderByChild('Team').on("value", function(snapshot) {
snapshot.forEach((child) => {
const childComplete = child.val().Team;
console.log(childComplete);
//There I get 2 teams
//FirstTeam
//SecondTeam
//First case
self.setState({TeamRequest: childComplete}, () => {
console.log(self.state.TeamRequest);
//There I get this
//FirstTeam
//FirstTeam
});
//Second case
this.setState({TeamRequest: childComplete}
console.log(self.state.TeamRequest);
//Log here is empty
});
});
});
}
return((函数
<ModalSelector onChange={ (option) => { this.GetTeamOption(option) } data={this.state.LeaguesToMapRequest}>
<TextInput value={this.state.LeagueOption} />
</ModalSelector>
constructor(props){
super(props);
this.state = {
Loaded: false,
Optionn:'',
LeagueOption: '',
TeamOption: '',
LeagueRequest: '',
TeamRequest: '',
TeamsToMapRequest: [],
LeaguesToMapRequest: []
}
}
GetTeamOption = (option) => {
let index = 0;
let object = {};
let TeamsArr = [];
this.setState({LeagueOption: option.label}, () => {
const refTeam = firebase.database().ref('leagues/' + this.state.LeagueOption + '/');
refTeam.orderByChild('Team').on("value", (snapshot) => {
snapshot.forEach((child) => {
const childComplete = child.val().Team;
console.log(childComplete);
//There I get 2 teams
//FirstTeam
//SecondTeam
//First case
this.setState({TeamRequest: childComplete}, () => {
console.log(this.state.TeamRequest);
//There I get this
//FirstTeam
//FirstTeam
});
//Second case
this.setState({TeamRequest: childComplete}
console.log(this.state.TeamRequest);
//Log here is empty
});
});
});
}
看起来您的问题是使用function
语句而不是箭头功能。箭头功能没有自己的范围,它们继承了范围。使用功能关键字将为您的功能提供自己的范围。我删除了对自我的引用。
您还可以在构造函数中使用this.GameTeamOption = this.GameTeamOption.bind(this);
将组件的this
上下文绑定到您的功能,也可以将其声明为箭头函数(这就是我采用的方法(。