gpt4 book ai didi

javascript - 单击 ReactJs 中的复选框时出现未定义错误

转载 作者:行者123 更新时间:2023-12-04 07:49:55 26 4
gpt4 key购买 nike

我是 ReactJS 的新手,我正在尝试制作一个待办事项列表。后端是 Java Spring Boot。
我只有一个复选框和一个字符串(字符串是列表的任务名称,例如“去购物”)
如果我单击复选框,则会收到错误消息:

A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component.


这是我的 App.js:
import { useEffect, useState } from 'react';
import './App.css';
import TodoItem from './components/todoItem';

function App() {

const [todoItems, setTodoItems] = useState(null);

useEffect(() => {
console.log("Hey loading");

if (!todoItems){
fetch('http://localhost:8080/api/todoItems')
.then((res) => res.json())
.then((data) => {
console.log("todo items list: ", data);
setTodoItems(data);
});
}
}, [todoItems]); //depends on todoItems
return (
<div>
{todoItems ? todoItems.map((todoItem) => {
return (
<TodoItem
key={todoItem.id}
data = {todoItem} />
);
})
: 'loading data..'}
</div>
);
}

export default App;
这是我的
待办事项.jsx
import React, { useEffect, useState } from 'react';

const TodoItem = (props) => {

const[todoItem, setTodoItem] = useState(props.data);
//const[getter, setter]
const [isDirty, setDirty] = useState(false);


useEffect( () => {
if(isDirty){
fetch('http://localhost:8080/api/todoItems/'+todoItem.id, {
method: 'PUT',
headers: {
"content-type": "application/json"
},
body: JSON.stringify(todoItem),
})
.then(response => response.json())
.then((data) => {
setDirty(false);
setTodoItem(data)
});
}
console.log("hey the todo is changing", todoItem);

}, [todoItem, isDirty]);

return (
<>
<input type ="checkbox" checked = {todoItem.isDone}
onChange={() => {
setDirty(true);
setTodoItem({ ...todoItem, isDone: !todoItem.isDone });
}}
/>
<span>{todoItem.task}</span>
</>
);
};

export default TodoItem;
我有点知道错误是因为复选框未定义。但我不明白为什么复选框未定义,因为它来自 App.js。
这是后端:
待办 Controller .java
@RestController
@CrossOrigin(origins = "http://localhost:3000")
public class ToDoController {

@Autowired
private TodoService todoService;

@RequestMapping(value = "/api/todoItems", method = RequestMethod.GET)
public ResponseEntity<?> fetchAllToDoItems(){
List<TodoItem> todoItemList = todoService.fetchAllTodoItems();
return ResponseEntity.status(HttpStatus.OK).body(todoItemList);

}

@RequestMapping(value="/api/todoItems/{id}", method = RequestMethod.PUT)
public ResponseEntity<?> updateTodoItem(@PathVariable Integer id, @RequestBody TodoItem todoItem){
TodoItem updateTodoItem =todoService.updateTodoItem(id, todoItem);
return ResponseEntity.ok(updateTodoItem);

}
}
待办服务.java
    @Service
public class TodoService {


@Autowired
private TodoRepository todoRepository;

public List<TodoItem> fetchAllTodoItems (){
return todoRepository.fetchAllTodoItems();
}

public TodoItem updateTodoItem(Integer id, TodoItem todoItem){
Optional<TodoItem> todoItemOptional = todoRepository.fetchAllTodoItems()
.stream()
.filter(item -> todoItem.getId().equals(id) )
.findAny();

if (todoItemOptional.isPresent()) {
TodoItem item = todoItemOptional.get();
item.setDone(todoItem.getDone());
item.setTask(todoItem.getTask());
return item;
}
return null;
}
}
ToDoRepository.java
@Repository
public class TodoRepository {
private Integer idCounter =0;

private List<TodoItem> todoItems = new ArrayList<>();

public List<TodoItem> fetchAllTodoItems() {
if (todoItems.size() == 0 ) {
TodoItem item1 = new TodoItem();
item1.setId(idCounter++);
item1.setDone(false);
item1.setTask("Task #1");

todoItems.add(item1);
}
return todoItems;

}

}
待办事项.java
public class TodoItem {


private Integer id;
private String task;
private Boolean isDone;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getTask() {
return task;
}

public void setTask(String task) {
this.task = task;
}

public Boolean getDone() {
return isDone;
}

public void setDone(Boolean done) {
isDone = done;
}
}

最佳答案

尝试更换 checkeddefaultChecked并且默认 Prop 为空,所以但很明显它是未定义的,因为您从空访问 isDone
添加 !!之前 todoItem.isDone

<input type ="checkbox" defaultChecked= {!!todoItem.isDone}
onChange={() => {
setDirty(true);
setTodoItem({ ...todoItem, isDone: !todoItem.isDone });
}}
/>


!!将值转换为 bool 值,所以 undefined 是假值,所以最终它会是假的

关于javascript - 单击 ReactJs 中的复选框时出现未定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67036960/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com