【发布时间】:2022-06-14 21:18:19
【问题描述】:
好的,伙计们,我已经被这件事困住了一段时间。我想我可能忽略了一些东西,或者..我的反应钩子错了。您可以在我的代码中指出的任何内容都会有所帮助和赞赏。
我正在开发我的待办事项应用程序。后端在这里:
const express = require('express');
const app = express();
const port = 5000;
const {loadList} = require('./todolist');
const cors = require('cors');
app.use(cors());
app.get('/todo', (req, res) => {
res.send(loadList());
})
app.listen(port, () => console.log(`Server running on port ${port}`));
这里是json文件:
{"title": "buy apples", "note": "1kg"},
{"title": "feed the cat", "note": "full bowl"}]
这是应用程序:
import Header from "./components/Header";
import Form from "./components/Form";
import TodoList from "./components/TodoList";
import "./App.css"
function App() {
return (
<div className="app-wrapper">
<Header />
<div>
<Form />
</div>
<TodoList />
</div>
);
}
export default App;
这是我需要帮助的组件:
import { useState, useEffect } from 'react';
const TodoList = () => {
const [ todos, setTodos ] = useState(null);
useEffect(() => {
fetch('http://localhost:5000/todo')
.then(res => res.json())
.then(data => setTodos(data.title))
})
return(
<div>
this is where the todolist should be
{todos}
</div>
)
}
export default TodoList;
感谢您的宝贵时间。
【问题讨论】:
-
您这里似乎没有问题。您采取了哪些步骤来调试此问题?您是否在控制台中收到任何错误?为什么是
setTodos(data.title)而不是setTodos(data)。也可能是useState([])而不是useState(null)。也许添加一个单独的if (!todos.length) return 'No data';
标签: javascript node.js reactjs