我是新来的本地人,我正在创建一个待办事项应用程序。当我将Todos状态初始化为非空数组时,我编写的组件将无限地重新渲染。这将导致错误,导致反应停止。我不知道是什么导致了无限循环,因为我没有包括任何递归或显式循环。我到处都添加了一些console.log(),发现deleteTodo和toggleTodo一直自动被调用,直到应用程序崩溃为止。
当Todos状态初始化为空数组时,出现一条错误消息,提示getTodos.map不是函数。
仅当状态更新为修改,添加或删除任务时,才期望重新渲染组件。
import React, { useState } from 'react'
import { Platform, StyleSheet, Text, View, TouchableHighlight } from 'react-native'
import { State, ScrollView } from 'react-native-gesture-handler'
/* All required imports are correctly added */
let id = 0
function TaskRow(props) {
return (
<View>
{/* empty button acting as checkbox */}
<TouchableHighlight>
<Text />
</TouchableHighlight>
{/* main text area, displays task and all details + tags*/}
<TouchableHighlight onPress={props.toggle(props.key)}>
<Text>{props.task}</Text>
</TouchableHighlight>
{/* delete button */}
<TouchableHighlight onPress={props.delete(props.key)}>
<Text>Delete</Text>
</TouchableHighlight>
</View>
)
}
export default function TodoList() {
const [
getTodos,
setTodos,
] = useState([
{ key: id, task: 'this is a task', checked: false },
])
const addTodo = (taskInput = 'sample') => {
id++
setTodos(getTodos.push({ key: id, task: 'task', checked: false }))
}
const deleteTodo = (deleteID) => {
setTodos(getTodos.filter((match) => match.key !== deleteID))
}
const toggleTodo = (toggleID) => {
setTodos(
getTodos.map((match) => {
if (match.key == toggleID) return { key: match.key, task: match.task, checked: !match.checked }
}),
)
}
return (
<View>
<TouchableHighlight onPress={addTodo}>
<Text>Add task</Text>
</TouchableHighlight>
<ScrollView>
{getTodos.map((task) => (
<TaskRow
key={task.key}
task={task.task}
delete={deleteTodo}
toggle={toggleTodo}
/>
))}
</ScrollView>
</View>
)
}
答案 0 :(得分:0)
在TaskRow
组件中存在问题,实际上在每个渲染器上您都在调用函数,而不是为事件声明处理程序。请以这种方式调整这两行:
// ...
<TouchableHighlight onPress={() => props.toggle(props.key)}>
// ...
<TouchableHighlight onPress={() => props.delete(props.key)}>
这是另一个问题:
setTodos(getTodos.push({ key: id, task: 'task', checked: false }))
.push()
不返回数组,因此您应该执行以下操作:
setTodos([...getTodos, { key: id, task: 'task', checked: false }])