简体   繁体   中英

How to get a specific item of a Flatlist in React-Native

How can I only render the item in a FlatList if the item.id is the same like the id in the json?

I'm new to react-native and JavaScript so maybe it's a stupid question.

My Code so far:

export default class DetailsScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      dataSource: [],
    };
  }

  componentDidMount() {
    this.setState({
      isLoading: false,
      dataSource: data.data
    });
  }

render() {
    if (this.state.isLoading) {
      return (
        <View>
          <ActivityIndicator />
        </View>
      );
    }
    return (
      <View>
        <FlatList
          data={this.state.dataSource}
          renderItem={({ item }) => (this.renderDetailView(item))}
          keyExtractor={(item, index) => index.toString()}
        />
      </View>
    );
  }
}

That's the simple rendering of the Flatlist and this work quite good. The 'renderDetailView' is very complex and long so I couldn't add the code.

But it look like this:

renderDetailView(item) {
    return (
      <View style={styles.info} key={item.id}>
        <View>
          <Text style={styles.detailView}>
            {item.name}
          </Text>
          <Text>{'\n'}</Text>
        </View>
         ...
      </View>
    );
  }

At the final project i want to handle a click on an other FlatList and show the detail of the clicked item. the clicked Item 'send' the id to this class and so i get the specific detailView.

Sorry for my bad English.

If you want to navigate to a detail page when you tap an item of your list you should use a navigation library ( react-navigation is the most popular).

I created a basic working example : https://snack.expo.io/@sanjar/so-53747271

(In this example I used react-navigation 2 while the last version is react-navigation 3, so use this one too if you want to reproduce it locally)

ps : I'm not sure to fully understand your requirements, you can add a comment if my answer was off topic or if you have any question

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM