首页 > 解决方案 > 无法从 flatList 中删除项目在 Api 的 react-native 中,

问题描述

无法从 flatList 中删除项目在来自 Api 的 react-native 中,ApiCard 是另一个组件,其中所需的数据项有一个 del 按钮。

      import React, {Component} from 'react'; import { StyleSheet, View, FlatList, Text, TouchableOpacity, SafeAreaView, Button, } from 'react-native'; import ApiCard from './ApiCard';
    export default class ApiList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      dataSource: [],
    };
  }
  static navigationOptions = {
    title: 'List of countries',
  };
  componentDidMount() {
    fetch('https://restcountries.eu/rest/v2/all')
      .then(response => response.json())
      .then(responseJson => {
        this.setState({
          loading: false,
          dataSource: responseJson,
        });
      })
      .catch(error => console.log(error)); 
  }
  render() {
    const {dataSource} = this.state;
    const {navigation} = this.props;
    return (
      <SafeAreaView style={styles.container}>
        <FlatList
          data={dataSource}
          keyExtractor={item => item.name}
          renderItem={data => (
            <ApiCard {...data.item} navigation={navigation} />

          )}
        />
      </SafeAreaView>
    );
  }
}

下面的组件用于将数据渲染为道具

import React from 'react';
import {TouchableOpacity, Text, StyleSheet, Button} from 'react-native';

const ApiCard = ({name, navigation, alpha2Code, population, capital}) => {
  return (
    <TouchableOpacity
      style={styles.country}
      onPress={() =>
        navigation.push('CountryName', {
          name,
          alpha2Code,
          population,
          capital,
        })
      }>
      <Text>{name}</Text>
      <Text>{alpha2Code}</Text>
      <Button title="del" /

在这里我需要一个 del 按钮操作它不删除任何东西并且删除操作不起作用

请帮我找到解决方案我尝试了所有方法但我无法删除它

    </TouchableOpacity>
  );
};

export default ApiCard;  

标签: reactjsreact-native

解决方案


您可能需要阅读更多有关 React 和 JS 的内容。但是通过的一种方法是创建一个方法/函数来更改和更新您的数据。

片段:示例是进行钻孔,即将方法从父级传递给子级。

//Assumption
const [datasource, setDataSource] = useState([])

//From your sample
const deleteItem = index => { 
   const arr = [...dataSource]; 
   arr.splice(index, 1); 
   setDataSource(arr); 
};

//You can use 'currying', meaning a partial function. 
onPressApiCard = (index) => () => {
   setLoading(true)
   deleteItem(index) //your index
} //method won't get executed until pressed as it's partial.

...
//pass index from data, see flatlist document
<FlatList
      data={dataSource}
      keyExtractor={item => item.name}
      renderItem={data => (
<ApiCard {...data.item} navigation={navigation} onPressCallback={onPressApiCard(data.index)}/>
...

从您的孩子(ApiCard)触发它。通常,您的子节点需要更新父组件。

//pass your data
const ApiCard = ({name, navigation, alpha2Code, population, capital, onPressCallback}) => 
//[Alternative], pass index here
//const ApiCard = ({name, navigation, alpha2Code, population, capital, onPressCallback, index}) => 
 ...
 return (
 <TouchableOpacity
  style={styles.country}
  onPress={() =>
    onPressCallback(); //Call the parent method
    //[Alternative] onPressCallback(index); //send index here.
    navigation.push('CountryName', {
      name,
      alpha2Code,
      population,
      capital,
    })
  }>

请注意,您将无法删除存储在state中的值。您需要更新状态而不是直接更改该值。请阅读有关反应状态提升state-lifting 的信息。

根据需要变得更复杂,您稍后需要检查“上下文”,“状态管理,如 redux/recoil”


推荐阅读