TypeError: Невозможно прочитать свойство 'map of undefined в React Native - PullRequest
0 голосов
/ 04 февраля 2019

Я делаю реакцию на родной проект.У меня есть массив данных, и в методе рендеринга я пытаюсь зациклить его, Это как некоторые пользовательские вкладки.Но, после загрузки, я пытаюсь переключиться с одной вкладки на другую, ошибка ее сброса и сбой, как enter image description here

TypeError: Can't read property 'map of undefined in React Native .

Мой код

dashboard.js
constructor(props) {
    super(props);
    this.state = { 
    selectedIndex:0,
    tabList:[
      {tabName: ‘Telugu’, tabActiveImage:TeluguActiveImg, tabInactiveImage: TeluguInActiveImg, tabActiveText:'black', tabInactiveText: 'gray'},
      {tabName: ‘Tamil’, tabActiveImage:TeluguActiveImg, tabInactiveImage: TeluguActiveImg, tabActiveText:'black', tabInactiveText: 'gray'},
      {tabName: ’Hindi’, tabActiveImage: HindiActiveImg, tabInactiveImage: HindiInActiveImg, tabActiveText:'black', tabInactiveText: 'gray'},
      {tabName: ‘English’, tabActiveImage: EnglishActiveImg, tabInactiveImage: EnglishInActiveImg, tabActiveText:'black', tabInactiveText: 'gray'},
    ]
}
 }

OnTabItemHandler = (index) => {
    this.setState({selectedIndex:index})
    console.log('selected index is',index)

}

    render(item) {
        const {tabList} = this.state;
        return (
<View>Some static data loading </View>
 <View style = {styles.tabContainer}>
            {
            //loop throught the state
            this.state.tabList.map((item,index)=>{
              return(
                //the style just to make it beautiful and easy to debug
                <View style ={styles.tabInnerContainer}>
                <TouchableOpacity style={styles.tabIcons}
                  //this onpress to handle of active selected tab
                onPress={()=>this.OnTabItemHandler(index)}
                >
                    <Image
                      //here's the magic show off
                      source={this.state.selectedIndex=index?item.tabActiveImage:item.tabInactiveImage}
                      style={styles.tabItemsImages}
                    />
                    <Text style={styles.tabItemTextBlackColor}>{item.tabName}</Text>
                </TouchableOpacity>
                </View>
              )
            })
        }
              </View>
              {this.renderBottomContent(item)}
          </View>


      );
    }
  }

и вид снизу основан на вкладке, я меняю вид снизу

 renderBottomContent = (item) => {


    this.state = { dataArray: getListData()}    

    switch(selectedTab) {
      case "Telugu":
        return <View style = {styles.flatListContainer}>  
    //show flat list data
         }
          ItemSeparatorComponent = {() => (
              <View style={{height:15, backgroundColor:'blue'}/>
          )}
      />
    </View >
      case "Tamil":
        return <View style = {styles.bottomStaicScreensForTabs}>
            <Text>
                Tamil feature will come
                </Text>
                </View>
     case "Hindi":
        return <View style = {styles.bottomStaicScreensForTabs}>
            <Text>
                Hindi feature will come
                </Text>
                </View>
    default:
        return <View><Text></Text></View>
    }
  }

А также цвет текста вкладки не меняется, всегда становится черным.Может ли кто-нибудь помочь мне, где я делаю неправильно.

enter image description here

1 Ответ

0 голосов
/ 05 февраля 2019

Чтобы лучше понять проблему, я создал перекус .Я опубликую код здесь на случай, если он больше не будет доступен.Примечание: он не стилизован должным образом, и изображения не являются динамическими, как вы и предполагали, но он может воспроизвести вопрос довольно хорошо.

  constructor(props) {
    super(props);
    this.state = {
      selectedIndex: 0,
      tabList: [
        {
          tabName: 'Telugu',
          tabActiveImage: '',
          tabInactiveImage: '',
          tabActiveText: 'black',
          tabInactiveText: 'gray',
        },
        {
          tabName: 'Tamil',
          tabActiveImage: '',
          tabInactiveImage: '',
          tabActiveText: 'black',
          tabInactiveText: 'gray',
        },
        {
          tabName: 'Hindi',
          tabActiveImage: '',
          tabInactiveImage: '',
          tabActiveText: 'black',
          tabInactiveText: 'gray',
        },
        {
          tabName: 'English',
          tabActiveImage: '',
          tabInactiveImage: '',
          tabActiveText: 'black',
          tabInactiveText: 'gray',
        },
      ],
    };
  }

  onTabItemHandler = index => {
    this.setState({ selectedIndex: index });
  };

  renderBottomContent = () => {
    const { selectedIndex, tabList } = this.state;
    const itemSelected = tabList[selectedIndex];
    switch (itemSelected.tabName) {
      case 'Telugu':
        return (
          <View style={{backgroundColor: 'yellow'}}>
            <Text>Telugu feature will come</Text>
          </View>
        );
      case 'Tamil':
        return (
          <View style={{backgroundColor: 'green'}}>
            <Text>Tamil feature will come</Text>
          </View>
        );
      case 'Hindi':
        return (
          <View style={{backgroundColor: 'cyan'}}>
            <Text>Hindi feature will come</Text>
          </View>
        );
      default:
        return (
          <View>
            <Text>No content</Text>
          </View>
        );
    }
  };

  render() {
    const { tabList, selectedIndex } = this.state;

    return (
      <View style={styles.container}>
        <Text>Some static data loading </Text>
        <View style={styles.tabContainer}>
          {//loop throught the state
          tabList.map((item, index) => {
            return (
              //the style just to make it beautiful and easy to debug
              <View style={styles.tabInnerContainer}>
                <TouchableOpacity
                  style={styles.tabIcons}
                  //this onpress to handle of active selected tab
                  onPress={() => this.onTabItemHandler(index)}>
                  <Image
                    //here's the magic show off
                    source={
                      selectedIndex === index
                        ? require('./assets/snack-icon.png')
                        : undefined
                    }
                    style={{ height: 30, width: 30 }}
                  />
                  <Text
                    style={{
                      color:
                        selectedIndex === index
                          ? item.tabActiveText
                          : item.tabInactiveText,
                    }}>
                    {item.tabName}
                  </Text>
                </TouchableOpacity>
              </View>
            );
          })}
        </View>
        {this.renderBottomContent()}
      </View>
    );
  }

Я все еще здесь для каких-либо разъяснений или улучшений.

Обновление Добавление стиля как:

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'flex-start',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  tabContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...