首页 > 解决方案 > 无法访问该状态,但我在调试器上看到它

问题描述

我有获取数据的功能,并且我确实setState将我的数据放入我的状态。

但我不明白如何在我的render()

getFixture = async () => {
    const url = 'http://127.0.0.1:80/testmatch/get_fixture.php';
    fetch(url).then((reponse) => reponse.json())
        .then((reponseJson) => { 
           this.setState({
                data:reponseJson,
                isLoading:false
            })
        })
    }
    componentDidMount(){
        this.getFixture()
    }

如果我console.log(this.state.data);在我的渲染中做一个在控制台中显示这个(在图像连接中)

如果我console.log(this.state.data.elapsed);正在工作并且我得到了价值,但如果我这样做了, console.log(this.state.data.awayTeam.logo);我会得到无法读取属性“徽标”

我不明白为什么。

截屏

这是所有代码,我想要的是使用从我的数据状态到我的渲染的所有数据:

getFixture = async () => {
        const url = 'http://127.0.0.1:80/testmatch/get_fixture.php';
         fetch(url).then((reponse) => reponse.json())
        .then((reponseJson) => { 
           this.setState({
                data:reponseJson,
                isLoading:false
            })
           console.log(this.state.data.awayTeam.logo); // WORKING (SHOW ME THE LINK)
        })
    }



render() {
   console.log(this.state.data.awayTeam.logo); // NOT WORKING (CANNOT READ PROPERTY OF UNDEFINED)
    return (
      <View style={styles.container}>
         <View style={styles.containerScore}>
            <View style={{flex: 1, flexDirection: 'row', borderColor:'#171F33',borderBottomWidth: 1 }}>

              <View style={{flex: 1,paddingTop:7,paddingBottom:7}}>
                 <View style={{flex: 1}}>
                 <Image style={{width: 50, height: 50}} source={{uri: "toto"}} />
                </View>
              </View>

              <View style={{flex: 1,paddingTop:7,paddingBottom:7, backgroundColor:'#fff'}}>
               <Text style={{fontSize:13}}> {this.state.data.elapsed}</Text>
              </View>

              <View style={{flex: 1,paddingTop:7,paddingBottom:7, marginLeft:2, backgroundColor:'#000'}}>
               <Text style={{fontSize:13}}></Text>
              </View>

            </View>

          <Text style={{color:"#FFF"}}>{} </Text>
         </View>

         <View style={styles.containerInfo}>


           <ScrollableTabView style={{marginTop: 1}} initialPage={0} renderTabBar={() => <CustomTabBar/>} >

            <View tabLabel='Tab #1'>
             <Text>My</Text>
            </View>

            <View tabLabel='Tab #2'>
            <Text>favorite</Text>
            </View>

            <View tabLabel='Tab #3'>
            <Text>favorite</Text>
            </View>

            <View tabLabel='Tab #4'>
            <Text>favorite</Text>
            </View>

            </ScrollableTabView>
         </View>
      </View>




    );
  }


}

标签: reactjsapireact-nativestatenative

解决方案


尝试像这样登录 setState 回调

   this.setState({
      data:reponseJson,
      isLoading:false
   }, () => {
      console.log(this.state.data.awayTeam.logo)
 })

推荐阅读