首页 > 解决方案 > 如何删除从列表中呈现的组件?反应原生

问题描述

我一直在关注ReactJS 的本教程,现在一直在尝试将简单的 Todo 应用程序(只是检查和检查项目)转换为 React Native。我一直在使用 expo 在我的手机和所有东西上进行实时试用。

一切都很顺利,但现在我正在尝试添加一些东西。每当我单击复选框时,我都想删除与该项目相关的组件。

我的想法是:

由于我从待办事项数组中渲染 TodoItem 组件,并且每当我单击一个复选框时,它都会更新整个数组(查找某个 id 并更新它的完成变量)。我可以遍历数组,只要 id 不同,我就会返回 todo。这样,我返回了所有待办事项,但要呈现具有匹配 id 的待办事项。

import React, { Component }  from 'react';
import { Alert,Image,StyleSheet, Text,Button, View } from 'react-native';
import TodoItem from './TodoItem'
import todosData from "./todosData"

export default class App extends React.Component {
  constructor() {
    super()
    this.state = {
      todos: todosData
    }

    this.handleChange = this.handleChange.bind(this)

  }


  handleChange(id) {
    this.setState(prevState => {
      const updatedTodos = this.state.todos.map( todo => {
    if(todo.id !== id) {
      return todo
    }

  })
  return {
    todos:updatedTodos
  }
})
  }
  render() {

const todoItems = this.state.todos.map( item =>
  <TodoItem
    key={item.id}
    item={item}
    handleChange = {this.handleChange}
  />
)
return (
  <View style={styles.container}>

    {todoItems}

  </View>
    );
  }
}

这给出了一个错误:'TypeError:undefined is not an object (evalating 'item.id')',在 App.js:42:18 给出

我还将添加引用 TodoItem 的代码:

import React, { Component }  from 'react';
import { Alert,Image,StyleSheet, Text,Button, View } from 'react-native';
import { CheckBox } from 'react-native-elements'
function TodoItem(props) {
  return (
    <View>
    <CheckBox
      checked={props.item.completed}
      onPress={() => props.handleChange(props.item.id)}
    />
    <Text>{props.item.text}</Text>


    </View>
  );
}
export default TodoItem

我不明白为什么这行不通。感觉就像我在使用它的同时删除了组件(因为它给出了未定义的值),但我不知道在哪里。因为我只是简单地更新待办事项列表。 我怎样才能做我想做的事?

PS:我似乎无法正确格式化第一段代码。我为此道歉!

标签: javascriptreactjsreact-native

解决方案


尝试这个:

handleChange(id) {
  const { todos } = this.state
  // filter out the deleted one
  const filtered = todos.filter(x => x.id !== id)

  this.setState({ todos: filtered })
}

我们不想直接更改状态,但是由于.filter()创建了一个新数组,而无需触及给定数组,因此可以使用它。如果它是另一个操作,你会做这样的事情:

// create a copy
const newSomethings = [...this.state.somethings]
// do whatever with newSomethings
this.setState({ somethings: newSomethings })

推荐阅读