mern - 更新后的值在数据中为空
mern - updated values are null in data
我正在尝试更新 post。后端的 PUT 请求工作正常,在 Postman 上测试时返回 200 并更新 posts 但是当我尝试在前端更新 post 时(反应),我没有收到任何错误,但更新的 post 未在提交时更新,并且 更新的字段(标题和 body)为空。 当我 console.log(data)
在前端,这就是它们没有被发送到后端但在 post
中正确显示的原因。
为什么更新后的值 null
在 data
里面?如何使用新值更新 post 而不是获取空值?
data:
post:
更新代码:前端
const EditPost = ({match}) => {
const [values, setValues] = useState({
title: "",
body: "",
error: ""
});
const [post, setPost] = useState({});
const { user, token } = isAuthenticated();
const {
title,
body,
error,
} = values;
const init = (id) => {
read(id).then(data => {
if (data.error) {
setValues({...values, error: data.error})
} else {
setValues({...values,
title: data.title,
body: data.body,
})
setPost({title: values.title, body: values.body})
}
})
}
useEffect(() => {
const id = match.params.id;
init(id);
}, []);
useEffect(() => {
setPost({...values });
}, [values.title, values.body]);
const handleChange = (name) => (event) => {
setValues({ ...values, [name]: event.target.value });
};
const clickSubmit = (event) => {
event.preventDefault();
setValues({ ...values, error: "" });
editPost(match.params.userId, match.params.id, token, post).then((data) => {
if (data.error) {
setValues({ ...values, error: data.error });
} else {
setValues({
...values,
title: "",
body: "",
error: false,
});
console.log(post)
console.log(data)
}
});
};
const newPostForm = () => (
<form onSubmit={clickSubmit}>
<div>
<input
onChange={handleChange("title")} type="text"
name="title"
value={title}
/>
</div>
<div className="form-group">
<textarea
onChange={handleChange("body")}
value={body} name="body"
/>
</div>
<button type="submit">Publish</button>
</form>
);
const showError = () => (
<div
style={{ display: error ? "" : "none" }}>
{error}
</div>
);
return (
<div>
{showError()}
{newPostForm()}
</div>
);
};
export default EditPost;
export const editPost = (userId, id, token, post) => {
return fetch(`${API}/${userId}/${id}/edit`, {
method: 'PUT',
headers: {
Accept: 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify(post)
})
.then(response => {
return response.json();
})
.catch(err => console.log(err));
};
postsByUser.js
<Link className="mypost_btn edit_btn" to={`/${_id}/${post._id}/edit`}>
Edit
</Link>
后端代码
exports.edit = (req, res) => {
if (!ObjectID.isValid(req.params.id))
return res.status(400).send(`ID is not valid: ${req.params.id}`)
const {title, body} = req.body
const updatedPost = {title, body }
Post.findByIdAndUpdate(req.params.id, {
$set: updatedPost
}, {new:true}, (error, data) => {
if (error) {
return error
} else {
res.send(data)
console.log(data)
}
})
}
在 EditPost.js editPost(match.params.userId, match.params.id, token).then((data) => {
中,您缺少第 4 个参数,即您发送要更新的“post”它自己
你的问题出在这里:
editPost(match.params.userId, match.params.id, token, post)
post
is not defined.
由于post
没有定义,所以没有传递数据。因此 title
和 body
等于 null
。根据我在您的代码中看到的情况,您需要做的是定义一个名为 post
的状态变量。我认为你打算这样做:
const [post, setPost] = useState({values.title, values.body});
然后确保您的 post 在您的 values
使用 useEffect()
、
更改时更新
useEffect(() => {
setPost({...values });
}, [values.title, value.body]);
因此,当您调用 editPost()
http-put-method 时,post 就有一个 value
。它应该可以工作。
我正在尝试更新 post。后端的 PUT 请求工作正常,在 Postman 上测试时返回 200 并更新 posts 但是当我尝试在前端更新 post 时(反应),我没有收到任何错误,但更新的 post 未在提交时更新,并且 更新的字段(标题和 body)为空。 当我 console.log(data)
在前端,这就是它们没有被发送到后端但在 post
中正确显示的原因。
为什么更新后的值 null
在 data
里面?如何使用新值更新 post 而不是获取空值?
data:
post:
const EditPost = ({match}) => {
const [values, setValues] = useState({
title: "",
body: "",
error: ""
});
const [post, setPost] = useState({});
const { user, token } = isAuthenticated();
const {
title,
body,
error,
} = values;
const init = (id) => {
read(id).then(data => {
if (data.error) {
setValues({...values, error: data.error})
} else {
setValues({...values,
title: data.title,
body: data.body,
})
setPost({title: values.title, body: values.body})
}
})
}
useEffect(() => {
const id = match.params.id;
init(id);
}, []);
useEffect(() => {
setPost({...values });
}, [values.title, values.body]);
const handleChange = (name) => (event) => {
setValues({ ...values, [name]: event.target.value });
};
const clickSubmit = (event) => {
event.preventDefault();
setValues({ ...values, error: "" });
editPost(match.params.userId, match.params.id, token, post).then((data) => {
if (data.error) {
setValues({ ...values, error: data.error });
} else {
setValues({
...values,
title: "",
body: "",
error: false,
});
console.log(post)
console.log(data)
}
});
};
const newPostForm = () => (
<form onSubmit={clickSubmit}>
<div>
<input
onChange={handleChange("title")} type="text"
name="title"
value={title}
/>
</div>
<div className="form-group">
<textarea
onChange={handleChange("body")}
value={body} name="body"
/>
</div>
<button type="submit">Publish</button>
</form>
);
const showError = () => (
<div
style={{ display: error ? "" : "none" }}>
{error}
</div>
);
return (
<div>
{showError()}
{newPostForm()}
</div>
);
};
export default EditPost;
export const editPost = (userId, id, token, post) => {
return fetch(`${API}/${userId}/${id}/edit`, {
method: 'PUT',
headers: {
Accept: 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify(post)
})
.then(response => {
return response.json();
})
.catch(err => console.log(err));
};
postsByUser.js
<Link className="mypost_btn edit_btn" to={`/${_id}/${post._id}/edit`}>
Edit
</Link>
后端代码
exports.edit = (req, res) => {
if (!ObjectID.isValid(req.params.id))
return res.status(400).send(`ID is not valid: ${req.params.id}`)
const {title, body} = req.body
const updatedPost = {title, body }
Post.findByIdAndUpdate(req.params.id, {
$set: updatedPost
}, {new:true}, (error, data) => {
if (error) {
return error
} else {
res.send(data)
console.log(data)
}
})
}
在 EditPost.js editPost(match.params.userId, match.params.id, token).then((data) => {
中,您缺少第 4 个参数,即您发送要更新的“post”它自己
你的问题出在这里:
editPost(match.params.userId, match.params.id, token, post)
post
is not defined.
由于post
没有定义,所以没有传递数据。因此 title
和 body
等于 null
。根据我在您的代码中看到的情况,您需要做的是定义一个名为 post
的状态变量。我认为你打算这样做:
const [post, setPost] = useState({values.title, values.body});
然后确保您的 post 在您的 values
使用 useEffect()
、
useEffect(() => {
setPost({...values });
}, [values.title, value.body]);
因此,当您调用 editPost()
http-put-method 时,post 就有一个 value
。它应该可以工作。