[英]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.