我一直在关注这个tutorial for ReactJS,现在一直在尝试将简单的Todo App(只需检查和打开项目)转换为React Native。我一直在使用expo来尝试在手机和其他设备上进行直播。
一切都很好,但是现在我正在尝试添加一些内容。每当我单击复选框时,我都希望删除与该项目相关的组件。
我的想法是:
由于我是从待办事项数组中渲染TodoItem组件, 当我单击一个复选框时,它将整体更新数组 (查找特定ID并更新其完成变量)。我可以 运行数组,并且每当id不同时,我都会返回 去做。这样,我返回了每个待办事项,但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不是对象(正在评估'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:我似乎无法正确格式化第一段代码。我为此表示歉意!
答案 0 :(得分:1)
尝试一下:
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 })