Импорт и связывание данных React Native ListView и SectionList

У меня есть несколько проблем как с пониманием, так и с передачей реквизитов и состояний, а также с навигацией.

Я использую Native Base 2.3.1, React Native 0.47.2 и React Navigate 1.0.0-beta.11.

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

https://medium.com/Differential/react-native-basics-how-to-use-the-listview-component-a0ec44cf1fe8

Это мой основной роутер

export const StackNav = new StackNavigator({
 Home: {
   screen: MainHome,
 },
 About: {
 screen: About,
 },
 Food: {
 screen: Food,
 },
 Poison: {
 screen: Poison,
 },
 Details: {
 screen: foodItem,
 path: 'foodItem/:food',
 }
}, {
 initialRouteName: "Home",
 mode: 'modal',
 headerMode: 'none'
},
);



export const FoodStack = new StackNavigator({
 Food: {
screen: Food,
navigationOptions: {
  title: 'Food',
   },
  },
  Details: {
   screen: foodItem,
  }
}, {
  initialRouteName: "Food",
  headerMode: 'none'
});

export const AppNavigator = new DrawerNavigator({
  Home: {
    screen: StackNav,
  },
 Food: {
screen: FoodStack,
  },
},  {
  initialRouteName: "Home",
 contentOptions: {
    activeTintColor: "#e91e63"
 },
  contentComponent: props => <MainDrawer navigation={props.navigation} drawerProps={{...props}} />
}
);`

Это моя страница со списком...

export default class Food extends React.Component {
  formatData(foodData) {
// We're sorting by alphabetically so we need the alphabet
    const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');

// Need somewhere to store our data
const dataBlob = {};
const sectionIds = [];
const rowIds = [];

// Each section is going to represent a letter in the alphabet so we loop over the alphabet
for (let sectionId = 0; sectionId < alphabet.length; sectionId++) {
  // Get the character we're currently looking for
  const currentChar = alphabet[sectionId];

  // Get users whose first name starts with the current letter
  const food = foodData.filter((food) => food.foodName.toUpperCase().indexOf(currentChar) === 0);

  // If there are any users who have a first name starting with the current letter then we'll
  // add a new section otherwise we just skip over it
  if (food.length > 0) {
    // Add a section id to our array so the listview knows that we've got a new section
    sectionIds.push(sectionId);

    // Store any data we would want to display in the section header. In our case we want to show
    // the current character
    dataBlob[sectionId] = { character: currentChar };

    // Setup a new array that we can store the row ids for this section
    rowIds.push([]);

    // Loop over the valid users for this section
    for (let i = 0; i < food.length; i++) {
      // Create a unique row id for the data blob that the listview can use for reference
      const rowId = `${sectionId}:${i}`;

      // Push the row id to the row ids array. This is what listview will  reference to pull
      // data from our data blob
      rowIds[rowIds.length - 1].push(rowId);

      // Store the data we care about for this row
      dataBlob[rowId] = food[i];
    }
  }
}

return { dataBlob, sectionIds, rowIds };
}
constructor(props) {
  super(props);

  const getSectionData = (dataBlob, sectionId) => dataBlob[sectionId];
  const getRowData = (dataBlob, sectionId, rowId) => dataBlob[`${rowId}`];

  const ds = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2,
sectionHeaderHasChanged : (s1, s2) => s1 !== s2,
getSectionData,
getRowData,
  });

  const { dataBlob, sectionIds, rowIds } = this.formatData(foodData);
  this.state = {
    dataSource: ds.cloneWithRowsAndSections(dataBlob, sectionIds, rowIds),
  };
}
render() {
    const {navigate} = this.props.navigation;
    return (
        <StyleProvider style={getTheme(wtwmNanonix)}>
        <Container>
        <Header androidStatusBarColor="#93278F" >
        <Left>
        <Button
        transparent
        onPress={()=>this.props.navigation.navigate('DrawerOpen')}>
        <Icon name="menu" />
      </Button>
        </Left>
            <Body>
                <Title></Title>
            </Body>
            <Right>
            <Button transparent><Icon name="share" /></Button>        
        <Button transparent><Icon name="search" /></Button>
        </Right>
        </Header>
        <View>
        <ListView 
        dataSource={this.state.dataSource}
        renderRow={(foodData) => <View><Text onPress={(foodData)=> this.props.navigation.navigate('Details', {...foodData})} >{foodData.foodName}</Text></View>} 
        renderSeparator={(sectionId, rowId) => <View key={rowId} style={styles.separator} />}
        renderHeader={() => <Search/>}
        rendersectionFooter={() => <sectionFooter />}
        renderSectionHeader={(sectionData) => <SectionHeader {...sectionData} />}

/>
      </View>
      </Container>
        </StyleProvider >


      );
}
}




module.export = Food

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

Я не возражаю, если я сделаю это с помощью SectionList, поскольку я не разделял вещи буквами алфавита. Хотя, если я сделаю это с помощью sectionlist, я не уверен, как использовать импорт данных, поскольку у меня уже есть существующий список, просмотрев множество руководств по этому вопросу.


person Arktix    schedule 04.09.2017    source источник


Ответы (1)


Что ж, в конце концов я догадался, и мне немного стыдно, что это было так просто: в моем файле строк мне нужно было добавить

const onRead = (food) => {
  this.props.navigation.navigate('Details', { ...food });
};

const Row = (props) => (
  <View style={styles.container} >
   <Text style={styles.text} onPress={() => this.onRead(props)} >
      {`${props.foodName}`}  
    </Text>
  </View>

);

export default Row;

Обратите внимание на строку

<Text style={styles.text} onPress={() => this.onRead(props)} >

реквизит был добавлен в this.onRead()

Таким образом, реквизит страницы не передавался правильно, хотя он видел значение, просто не правильное. Так что ошибок как таковых не было. Надеюсь, это поможет кому-нибудь в будущем.

person Arktix    schedule 18.09.2017