【问题标题】:Not able to delete items from flatList In react-native from Api,无法从 flatList 中删除项目在 Api 的 react-native 中,
【发布时间】:2021-08-06 14:48:58
【问题描述】:

无法从 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>
    );
  }
}

Below 组件用于将数据渲染为道具

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;  

【问题讨论】:

    标签: reactjs react-native


    【解决方案1】:

    您可能需要阅读更多有关 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”

    【讨论】:

    • 只有第一个元素被删除无论你点击任何项目,delteitemData 只删除第一个项目..下面是删除项目的代码,这里我使用了拼接方法..请帮我解决... const deleteItem = index => { const arr = [...dataSource]; arr.splice(索引,1);设置数据源(arr); }; onPressApiCard = () => { setDataSource(index => { deleteItem(index); }); };
    • @HemaSai,deleteItem的方法是正确的。但是“onPressApiCard = () => { setDataSource(index => { deleteItem(index); }); };”是模棱两可的。 #1 你的索引来自哪里,它似乎总是通过 0。
    • @HemaSai 更新代码。但是可能需要一些时间来消化,无论如何你的目标是弄清楚如何发送你的“索引”进行删除。
    • 这个Bug有什么解决办法可以去掉..???
    • @HemaSai 这不是一个错误,它是一个标准的 JavaScript。因为您需要传递参数并且 onPress/onClick 仅将事件作为参数发送。我知道要消化很多东西,但是如果你加强你的 JS,以后更容易吸收(我也不是专家)。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多