NodeJS 在发布动态数据时遇到问题,我得到的是静态数据而不是动态数据

i34xakig  于 11个月前  发布在  Node.js
关注(0)|答案(1)|浏览(189)

这里是我的React的代码,我也分享了一个图像的数据,这是得到后,张贴动态数据.我后,你好世界从输入字段“添加新的待办事项任务”,但我越来越多的数据实践,以获得更多的经验.如何获得动态数据?


的数据

import React, { useState, useEffect } from 'react';
import axios from "axios";
import deleteIcon from "./assets/delete.png";
import './App.modules.css';

const BASE_URL = "http://localhost:5000/api";

function App() {
  const [todos, setTodos] = useState(null);
  const [todo, setTodo] = useState("")

  useEffect(() => {
    getTodos()
  }, []);
const getTodos = () => {
     axios.get(`${BASE_URL}/todos`)
    .then((res) => setTodos(res.data))
    .catch((err) => console.log("Error getting todos", err))
  };

  const handleAddTodo =  () => {
    axios.post(`${BASE_URL}/todo/new`, {title : "Practice more to gain more experience"})
    .then((res) => {
      setTodos([...todos, res.data]);
      setTodo("");
    })
    .catch((err) => console.log("Error adding todo", err));
  };

  const handleDeleteTodo = (id) => {
    axios
    .delete(`${BASE_URL}/todo/delete/${id}`)
    .then((res) => 
        setTodos(todos.filter((todo) => todo._id !== res.data._id))
    )
      .catch((err) => console.log(err));
  };

  const handleTodoClick = (id) => {
    axios.get(`${BASE_URL}/todo/toggleStatus/${id}`)
    .then((res) => getTodos())
    .catch((err) => console.log(err))
  };

    return (
    <div className="App">
    <div className='todo-input-wrapper'>
      <input 
        className='todo-input-bar'
        value={todo}
        onChange={(e) => setTodo(e.target.value)}
        placeholder='Add a New Todo Task'  />
        <div className='add-button' onClick={handleAddTodo}>
          +
        </div>
    </div>
    <div className='todos-list'>
      {!todos || !todos.length ? (
          <h2 style={{textAlign : "center" }}>No Tasks Yet Found</h2>
        ) : (
          todos.map((todo) => (
            <div className='todo' key={todo._id}>
              <span onClick={() => handleTodoClick(todo._id)}
              className={todo.complete ? "complete" : ""}
              id='todo-title' >
                {todo.title}
              </span>
              <span className='delete'
              onClick={()=> handleDeleteTodo(todo._id)}>
                <img src={deleteIcon} alt='delete' height="20px" width="20px" />
              </span>
            </div>
          ))
        )
      }
    </div>
 </div>
 )
}

export default App;

字符串
我尝试获取hello,world,但是我获取的是静态数据,所以现在我想获取动态数据,而不是静态数据


aemubtdh

aemubtdh1#

看起来在你的handleAddTodo函数中,你在每次调用函数时都硬编码了todo标题。因此,它为每个API调用保存相同的标题字符串。通过使标题动态化来重构AddAddTodo方法。这应该可以工作:

const handleAddTodo =  () => {
    axios.post(`${BASE_URL}/todo/new`, {title : todo})
    /*
     *Rest of the code
    */

  };

字符串

相关问题