React JS结合Express/Node读取JSON文件时fetch数据卡住问题求助
Todo应用fetch卡住问题排查修复
你的代码共存在4处直接导致异常的问题,按优先级修复即可解决:
1. 待办存储JSON文件格式非法
当前存储待办数据的JSON文件缺失数组起始符号[,不属于合法JSON结构,后端读取解析时会直接报错,导致接口无法返回正常响应,前端请求无法拿到预期结果。
当前错误内容:
{"title": "buy apples", "note": "1kg"}, {"title": "feed the cat", "note": "full bowl"}]
修复后正确内容:
[ {"title": "buy apples", "note": "1kg"}, {"title": "feed the cat", "note": "full bowl"} ]
2. useEffect缺少依赖数组触发无限请求死循环
你写的useEffect没有传入第二个依赖数组参数,组件每次重渲染都会重新执行fetch请求;请求完成后调用setTodos更新状态又会触发组件重渲染,再次发起请求,形成无限循环,表现为请求一直卡住、页面无响应。
修复方式是给useEffect传入空依赖数组,让请求仅在组件首次挂载时执行1次。
3. 接口返回值取值逻辑错误
后端/todo接口返回的是待办事项数组,不存在.title属性,你写的setTodos(data.title)最终只会存入undefined。这里直接把接口返回的完整数组存入状态即可。
4. 渲染逻辑未适配数据结构
初始状态下todos值为null,且最终todos是数组结构,无法直接在JSX中渲染,需要遍历数组生成对应列表项,建议将初始值改为空数组避免渲染异常。
修复后可正常运行的TodoList组件完整代码:
import { useState, useEffect } from 'react'; const TodoList = () => { const [ todos, setTodos ] = useState([]); useEffect(() => { fetch('http://localhost:5000/todo') .then(res => { if (!res.ok) throw new Error('接口响应异常') return res.json() }) .then(data => setTodos(data)) .catch(err => console.error('请求出错:', err)) }, []) return( <div> this is where the todolist should be {todos.map((todo, index) => ( <div key={index} className="todo-item"> <h4>{todo.title}</h4> <p>{todo.note}</p> </div> ))} </div> ) } export default TodoList;
内容的提问来源于stack exchange,提问作者uztonejsemja
相关产品推荐
相关产品推荐

