简体   繁体   English

创建 Todo 后,它会在 React 中请求获取 Todos。 我想在列表下做todo而不刷新页面

[英]After create a Todo, it make a request get Todos in React. I want to todo under the list without refreshing the page

I want to create a todo, but after create a todo I want to not refresh all the list, but when I create a post request it also creates refresh and get request我想创建一个待办事项,但在创建一个待办事项后我不想刷新所有列表,但是当我创建一个发布请求时它也会创建刷新和获取请求

const App = () => {
  const dispatch = useDispatch()
  const [hamburgerMenu, setHamburgerMenu] = useState(false);

  const { authReducer } = useSelector(state => state)

  useEffect(() => {
    dispatch(refreshToken())
  }, [dispatch])

  return (
    <Router>
      <Alert />
      <Navbar
        hamburgerMenu={hamburgerMenu}
        setHamburgerMenu={setHamburgerMenu}
      />
      <Menu
        hamburgerMenu={hamburgerMenu}
        setHamburgerMenu={setHamburgerMenu}
      />
    
      <Routes>
        <Route exact path="/login" element={<Login />} />
        <Route exact path="/register" element={<Register />} />
        {<Route exact path="/" element={!authReducer?.access_token ? <HomepageLogout/> : <Homepage/>} /> }
      </Routes>
    </Router> 
  )
}

export default App
import { useEffect } from "react"
import TodoList from "../components/TodoList"
import { useSelector, useDispatch } from "react-redux"
import { getTodos } from "../redux/actions/todoAction"
import './styles/homepage.scss'

const Homepage = () => {
  const dispatch = useDispatch()

  const { authReducer, todoReducer } = useSelector((state) => state)
  const userId = authReducer?.user?.userId
  const access_token = authReducer?.access_token

  useEffect(() => {
    userId &&  dispatch(getTodos(userId))
  }, [userId, dispatch ]);

  const todoList = todoReducer?.data

  return (
    <div style={{ width: "100%", height: "100vh", display: 'flex', flexDirection: 'column', alignItems: "center", justifyContent: "center" }}>
      <TodoList  todoList={todoList} access_token={access_token} />
    </div>
  )
}

export default Homepage
import Todo from "./Todo"
import "./styles/todoList.scss"
import TodoForm from "./TodoForm"

const TodoList = ({ todoList, access_token, setIsAdded }) => {
  return (
    <div style={{ display: 'flex', flexDirection: 'column' }}>
      <div className="todoListContainer">
        <h1 className="title2">What are you planing for today?</h1>
        <ul className="todoListContainer__listContainer">
          {todoList &&
            todoList?.map((todo) => {
              return (
                <Todo todoList={todoList} todo={todo} key={todo?.todoId} access_token={access_token} />)
            })
          }
        </ul>
        <TodoForm todoList={todoList}  />
      </div>
    </div>
  )
}

export default TodoList
import { useState } from 'react'
import { useSelector, useDispatch } from "react-redux"
import { createTodo } from "../redux/actions/todoAction"
import "./styles/todoForm.scss"

const TodoForm = ({ todoList }) => {
  const dispatch = useDispatch()
  const { authReducer } = useSelector(state => state)

  const token = authReducer?.access_token
  const userId = authReducer?.user?.userId

  const initialState = {
    text: "",
    todoUserId: userId
  }

  const handleSubmit = (e) => {
    userId && dispatch(createTodo(todo, token, todoList))
  }

  const handleChange = (e) => {
    const { value, name } = e.target
    setTodo({
      ...todo,
      [name]: value
    })
  }

  const [todo, setTodo] = useState(initialState)

  return (
    <form className="todoForm" onSubmit={handleSubmit}>
      <input
        placeholder="Please add something.."
        id="text"
        name="text"
        type="text"
        value={todo?.text}
        onChange={handleChange}
      />
      <input
        id="todoUserId"
        name="todoUserId"
        value={todo?.todoUserId}
        readOnly
        style={{ display: 'none' }}
      />

      <button type="submit">
        Add
      </button>
    </form>
  )
}

export default TodoForm

TODO ACTION待办事项

export const createTodo = (todo, token, todoList) => async (dispatch) => {
  try {
    const res = await postAPI("/todo/create", todo, token);
    dispatch({
      type: TODO,
      payload: {
        status: "success",
        message: "All todos found",
        data: todoList.append(todo)
      } 
    })
    dispatch({ type: ALERT, payload: { success: res.data.message } })
  } catch (error) {
    dispatch({ type: ALERT, payload: { errors: error?.response?.data.message } })
  }
};

POSTAPI邮政API

export const postAPI = async (url, post, token) => {
  const res = await axios.post(`/api/${url}`, post, {
    headers: { token: token }
  })

  return res
}

I have tried todoList with useState() also different array methods in payload in action but still it creates get and refresh request.我已经尝试使用todoList useState()的 todoList 在有效载荷中使用不同的数组方法,但它仍然创建获取和刷新请求。 It is bad for me because when I create a todo, access_token becomes for a second undefined, so the list disappears and comes another component.这对我来说很糟糕,因为当我创建一个待办事项时, access_token变为未定义,因此列表消失并出现另一个组件。 I want to add todo under the list without refreshing the page我想在不刷新页面的情况下在列表下添加todo

Here my logs after create a todo这是我创建待办事项后的日志

POST /api/todo/create 200 286.656 ms - 249
GET /api/refresh_token 200 200.426 ms - 408
GET /api/refresh_token 304 3.712 ms - -
GET /api/todo/get/emrekrt163395 200 4.840 ms - 7491
GET /api/todo/get/emrekrt163395 304 10.143 ms - -

It seems the page is reloading because the form is being submitted when clicking the "add" button.似乎页面正在重新加载,因为单击“添加”按钮时正在提交表单。 The default form action is not being prevented.默认表单操作未被阻止。 handleSubmit should call preventDefault on the passed onSubmit event object to prevent the default form action from submitting the form and reloading the page ( and entire React application ). handleSubmit应该在传递的onSubmit事件对象上调用preventDefault以防止默认表单操作提交表单和重新加载页面(以及整个 React 应用程序)。

Example:例子:

const handleSubmit = (e) => {
  e.preventDefault(); // <-- prevent submitting the form

  if (userId) {
    dispatch(createTodo(todo, token, todoList));
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我在待办事项列表中得到重复的待办事项? - Why I get duplicated todos in todo list? 更新待办事项列表,而无需在express nodejs应用程序中刷新页面 - Update the todo list without refreshing the page in express nodejs app 我可以存储在 LOCAL STORAGE 但刷新页面后列表仍然消失了? 带有 Javascript 的基本待办事项列表应用程序 - I can store in LOCAL STORAGE but the lists are still gone after refreshing the page? basic Todo list app with Javascript 我想在 javascript 中创建待办事项列表的完整 function - I want to create complete function of todo list in javascript React Todo列表-如何使过滤器起作用 - React todo list - how to make the filter work React 待办事项列表显示待办事项 onChange,而不是 onSubmit - React todo list displays todo onChange, not onSubmit 我想在样本Todo应用程序中为ember.js嵌套待办事项 - I want to have nested todos in Sample Todo Application for ember.js 使用 Javascript 创建待办事项列表 - Create Todo list with Javascript 我想制作一个待办事项列表,但我一开始就卡住了,我在这段代码中哪里出错了? - i want to make a todo list but i m stuck at the starting, where am i getting wrong in this code? 为什么“ this.todos = […this.todos,todo]”而不是推送? - Why “this.todos = […this.todos, todo] ” and not push?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM