如何将tabsDidMount用于标签?

问题描述 投票:0回答:1

我有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',
});
react-native react-navigation
1个回答
1
投票

您正在获得的错误是因为当您的fetch正在等待响应时,render函数正在尝试使用非现有数据源呈现ListView

您可以通过将状态中的初始值设置为空数据源来修复此问题,或者,在渲染函数中添加一个检查,如果数据源不为null,则仅检查ListView

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

最后,ListView已被弃用,已被具有更友好API的FlatList所取代。

© www.soinside.com 2019 - 2024. All rights reserved.