【问题标题】:got stuck on fetching data in react js (using express, nodejs, json file)卡在 React js 中获取数据(使用 express、nodejs、json 文件)
【发布时间】: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


【解决方案1】:

React 钩子看起来不错。错误是什么?你没看到你的待办事项还是什么?待办事项是否存储在服务器上?有很多选项可能会出错。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-20
    • 2018-08-14
    • 2022-01-26
    • 2018-10-23
    • 2021-11-10
    • 1970-01-01
    • 2020-10-15
    • 1970-01-01
    相关资源
    最近更新 更多