如何将componentDidMount用于标签?

时间:2019-04-23 11:08:57

标签: react-native react-navigation

我在react-navigationcreateMaterialTopTabNavigator处有三个标签。现在,我想在jsoncomponentDidMount的标签中显示一些数据,但是当我在两个标签中放置componentDidMount时出现此错误:

  

null不是对象(正在评估'this.state.dataSource')

当我在一个标签中使用componentDidMount时,一切正常,并且运行正常。

我的一个标签页:

export default class HomeTabScreen extends React.Component{

componentDidMount(){
    return fetch('men-cat.php')
    .then((response)=>response.json()).
    then((responseJson)=>{
      let ds = new ListView.DataSource({rowHasChanged:(r1,r2)=>r1!=r2});
      this.setState({
        isLoading:false,
        dataSource:ds.cloneWithRows(responseJson)
      });
    }).done();
  }

  render() {
    return (
      <ScrollView>
      <ListView style={{zIndex:1}}
        contentContainerStyle={styles.list}
        dataSource={this.state.dataSource}
        enableEmptySections={true}
        renderRow={ (rowData)=>

            <View style={styles.cats}>
              <TouchableOpacity activeOpacity={0.8} onPress={()=>{this.props.navigation.navigate('Products' , {
                title: rowData.name,
              })}}>
                <ImageBackground source={{uri:rowData.thumb}} imageStyle={{ borderRadius: 5 }} style={styles.imgBgCats}>
                  <Text style={styles.homeCatsCostTitle}>{rowData.name}</Text>
                </ImageBackground>
              </TouchableOpacity>
            </View>
          }
          />
    </ScrollView>

    );
  }
}

根:

const MenStack = createStackNavigator({
  menStackNav: { screen: MenTabScreen,    navigationOptions:{tabBarVisible: false},
},
  Products: {
    screen: ProductsShow,
    navigationOptions:{tabBarVisible: false},
  },
},{
  initialRouteName: 'menStackNav',
  headerMode: 'none',
  navigationOptions: {
    headerVisible: false,
  }
});

MenStack.navigationOptions = ({navigation}) => {
      let tabBarVisible = true;
      if(navigation.state.index > 0){
        tabBarVisible = false;
      }

      return {
        tabBarVisible,
      }
}

const HomeScreenTabs = createMaterialTopTabNavigator({
  Home:{
    screen:HomeTabScreen,
  },
  Women: {
    screen:WomenTabScreen,
  },
  Men: {
    screen:MenStack,
  },

},{
  tabBarOptions: {
    style:{backgroundColor:'#fff'},
    activeTintColor: '#0077FF',
    inactiveTintColor: '#0077FF60',
    indicatorStyle: {
      opacity: 0
    },
    tabStyle:{backgroundColor:'#fff',height:40,borderBottomColor:'#fff'},
    labelStyle: {
      borderBottomColor:'#fff',
        fontSize: 14,
      },
  },
    initialRouteName: 'Men',
    mode: 'modal',
    headerMode: 'none',
});

1 个答案:

答案 0 :(得分:1)

您遇到的错误是由于在获取操作等待响应时,呈现函数正在尝试使用不存在的数据源呈现ListView

您可以通过将状态的初始值设置为空的数据源来解决此问题,或者在渲染函数中添加仅在数据源不为null时渲染ListView的检查功能。 / p>

{!!this.state.dataSource &&
 <ListView
    ...
 />}

最后,ListView已过时,已被具有更友好API的FlatList取代。