【发布时间】:2021-06-18 09:52:50
【问题描述】:
我正在尝试更新表单,但某些内容无法正常工作。我点击更新后,控制台中记录了更新的信息,但是状态管理的redux端好像不行。我在控制台中没有收到任何错误,但我的操作 UPDATE_POST 在 Chrome 上的 Redux 开发工具中都不可见。
代码如下:
UpdateForm 组件:
import { useState , useEffect} from "react";
import { useHistory, useParams } from 'react-router-dom';
import jsonPlaceholder from "../apis/jsonPlaceholder";
import {updatePost} from '../actions'
import { useDispatch } from 'react-redux';
const UpdateForm = () => {
const dispatch = useDispatch()
const history = useHistory();
const { id } = useParams();
const [post, setPost] = useState({});
const [title, setTitle] = useState(post.title);
const [body, setBody] = useState(post.body);
const [author, setAuthor] = useState(post.author);
const fetchPost = async () => {
const response = await jsonPlaceholder.get(`/posts/${id}`)
console.log(response.data)
setPost(response.data)
setTitle(response.data.title)
setBody(response.data.body)
setAuthor(response.data.author)
return response.data
}
useEffect(() => {
fetchPost();
}, [])
const handleUpdate = async (e) => {
e.preventDefault();
const post = { title, body, author }
dispatch(updatePost(post))
console.log('post', post)//updated post is logged in console
history.push('/')
}
console.log("title", title)
return (
<div className="create">
<h2>Update Blog</h2>
<form>
<label>Blog title:</label>
<input
type="text"
required
defaultValue={title}
onChange={(e) => setTitle(e.target.value)}
/>
<label>Blog body:</label>
<textarea
required
defaultValue={body}
onChange={(e) => setBody(e.target.value)}
></textarea>
<label>Author:</label>
<input
type="text"
required
defaultValue={author}
onChange={(e) => setAuthor(e.target.value)}
/>
<button onClick={handleUpdate}>Update</button>
</form>
</div>
);
}
export default UpdateForm;
动作:
export const updatePost = (post) => async dispatch => {
const res = await jsonPlaceholder.put(`posts/update/${post._id}`);
dispatch({
type: UPDATE_POST,
payload: res.data
})
}
还有减速器:
import { ADD_POST, DELETE_POST, UPDATE_POST } from '../actions/types';
const postReducer = (state = [], action) => {
switch (action.type) {
case ADD_POST:
return state.concat([action.data]);
case UPDATE_POST:
return {
...state,
post: action.data
}
case DELETE_POST:
return state.filter((post)=>post.id !== action.id);
default:
return state
}
}
export default postReducer;
这里是请求的 node.js/express 服务器端:
router.put('/update/:id', async (req, res) => {
try {
let post = await Post.findOneAndUpdate(req.params.id, {
title: req.body.title,
body: req.body.body,
author: req.author.body
})
console.log('server', post)
return res.json(post)
} catch (error) {
console.error(error.message);
res.status(500).send('Server Error')
}
})
我现在收到服务器错误 (500),如果我删除行 author: req.author.body,我不会收到错误。前面的代码还是不行。
【问题讨论】:
-
你的代码看起来不错。你能在
const res = await jsonPlaceholder.put('posts/update/${post._id}');后面加一个console.log(res)吗? -
好像也有服务器错误。这是请求。 router.put('/update/:id', async (req, res) => { try { let post = await Post.findOneAndUpdate(req.params.id, { title: req.body.title, body: req. body.body,作者:req.author.body }) console.log('server', post) return res.json(post) } catch (error) { console.error(error.message); res.status(500 ).send('服务器错误') } })
-
顺便说一句,这是我在控制台记录响应时得到的:url:“posts/update/undefined”,方法:“put”,标题:{…},baseURL:“localhost:500以及错误的 response.data 对象(它返回的对象的 id 与单击的对象不同)
-
将
author: req.author.body替换为author: req.body.author并检查res.data在您的前端代码中是否正确 -
嗯,感谢您发现这一点。我替换了它,现在它在 Postman 上运行良好,只是我需要发送两次请求(第一次返回 null,第二次返回数据)。
标签: reactjs forms redux react-redux put