[英]Can i set the state here? React-Native
In the getMatches function, I want to set the state, with the matches associated with the leagueID. 在getMatches函数中,我想设置状态以及与LeagueID相关的匹配项。 Where I am running into problems is how to setState in the get Matches function.The fetch response gives me exactly what I want back.
我遇到问题的地方是如何在get Matches函数中设置setState.fetch响应给出了我想要返回的确切信息。 Its an array with matches associated with the LeagueID.
它是一个与LeagueID关联的匹配项的数组。 That setState will run twice because I am using 2 leagueIds.
该setState将运行两次,因为我使用了2个LeagueIds。 Any help or advice would be greatly appreciated.
任何帮助或建议,将不胜感激。
export default class MatchView extends Component { state = { matches: null, leagueName: null } componentWillMount = () => { this.getLeagueNames(); }//end componentwwillMOunt // componentDidMount = () => { // console.log("league_array", this.state.leagueName) // } getLeagueNames = () => { let leagueArray = []; fetch(`https://apifootball.com/api/?action=get_leagues&APIkey=42f53c25607596901bc6726d6d83c3ebf7376068ff89181d25a1bba477149480`) .then(res => res.json()) .then(leagues => { leagues.map(function(league, id){ leagueArray = [...leagueArray, league] })//end .map this.setState({ leagueName: leagueArray }); }) }// end getLeagueNames getMatches = (leagueID) => { let LeagGamesArray = []; console.log('working') fetch(`https://apifootball.com/api/?action=get_events&from=2016-10-30&to=2016-11-01&league_id=${leagueID}&APIkey=42f53c25607596901bc6726d6d83c3ebf7376068ff89181d25a1bba477149480`) .then(res => res.json()) .then(fixtures => { LeagGamesArray = [...LeagGamesArray, fixtures] ** this.setState({ matches: LeagGamesArray }) ** Setting the state here dosent work, just keeps running the code over and over again.**strong text** }) } //console.log(this.state.matches) //console.log(this.state.matches) //console.log(this.state.matches) renderItem = () => { if(this.state.leagueName != null){ return this.state.leagueName.map(function(league){ let leagueID = league.league_id let fix = this.getMatches(leagueID) //console.log(fix) return ( <LeagueName key={league.country_id} league={league}/> ) }.bind(this))//end maps..We .bind(this) b/c we want to change the meaning of this. We first use it in the .map function, but we also want to use this to call the getMacthes function. } else { return null; } }//end renderItem render(){ return ( <ScrollView> {this.renderItem()} </ScrollView> ) } }
strong text 强文本
Your renderItem
method calls getMatches(leagueID)
, which in turn fires-off your fetch
which results in setState
and a subsequent render
... and repeat. 您的
renderItem
方法调用getMatches(leagueID)
,这反过来触发您的fetch
,从而导致setState
和随后的render
...并重复。
You should call getMatches
from elsewhere, like componentWillMount
. 您应该从其他地方调用
getMatches
,例如componentWillMount
。 Or by some user interaction (or even timer) that you use to generate a refresh. 或者通过一些用户交互(甚至是计时器)来生成刷新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.