蕪湖不蕪
2022-10-27 14:17:29
這是 react 中一個(gè)簡(jiǎn)單的 TO-DO 應(yīng)用程序,它從中App.js獲取數(shù)據(jù),TodosData.js列表與組件一起顯示TodoItem.js?,F(xiàn)在可以在渲染時(shí)查看復(fù)選框和數(shù)據(jù)。但是當(dāng)我點(diǎn)擊復(fù)選框時(shí)它不起作用。我嘗試handleChange了似乎有效的控制臺(tái)日志記錄功能。似乎handleChange函數(shù)內(nèi)部可能存在我無(wú)法弄清楚的問(wèn)題。我正在關(guān)注 YT 上的 freecodecamp 教程,我也檢查了幾次,但在這里找不到問(wèn)題。App.js代碼:import React from 'react';import TodoItem from './TodoItem'import todosData from './todosData'class App extends React.Component { constructor() { super () this.state = { todos: todosData } this.handleChange = this.handleChange.bind(this) } handleChange(id) { this.setState(prevState => { const updatedTodos = prevState.todos.map(todo => { if (todo.id === id) { todo.completed = !todo.completed } return todo }) return { todos: updatedTodos } }) } render() { const todoItems = this.state.todos.map(itemEach => <TodoItem key = {itemEach.id} itemEach = {itemEach} handleChange = {this.handleChange} />) return ( <div className = "todo-list"> {todoItems} </div> ) }}export default App;TodoItem.js代碼:import React from 'react';function TodoItem(props) { return( <div className = "todo-item"> <input type = "checkbox" checked={props.itemEach.completed} onChange={() => props.handleChange(props.itemEach.id)} /> <p>{props.itemEach.text}</p> </div> )}export default TodoItemTodosData.js代碼:const todosData = [ { id: 1, text: "Take out the trash", completed: true }, { id: 2, text: "Grocery shopping", completed: false }, { id: 3, text: "Clearn gecko tank", completed: false }, { id: 4, text: "Mow lawn", completed: true }, { id: 5, text: "Catch up on Arrested Development", completed: false }]export default todosData有沒有更好的方法來(lái)實(shí)現(xiàn)這一點(diǎn)?對(duì)于像我這樣的初學(xué)者來(lái)說(shuō),這種做復(fù)選框的方式似乎相當(dāng)復(fù)雜。另外我該如何改進(jìn)這段代碼?
1 回答

明月笑刀無(wú)情
TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超4個(gè)贊
您正在改變handleChange函數(shù)中的狀態(tài)。因此它得到了prevState兩次。一次用于原始先前狀態(tài),接下來(lái)用于您在handleChange.
todo通過(guò)像這樣傳播 from 狀態(tài),您可能會(huì)丟失參考。
this.setState(prevState => {
const updatedTodos = prevState.todos.map(todo => {
const resTodo = { ...todo };
if (todo.id === id) {
resTodo.completed = !resTodo.completed;
}
return resTodo;
});
return {
todos: updatedTodos
};
});
這是一個(gè)有效的代碼框
添加回答
舉報(bào)
0/150
提交
取消