我做一个CRUD博客类似的应用程序,当我POST或编辑博客时,我使用history.push()重定向用户,但是当用户被重定向时,如果我刷新页面,内容更新,信息仍然是旧的。过去的一天我到处都找遍了,但我似乎找不到问题的答案。下面是我更新信息的组件,例如
import { useState, useEffect, useRef } from "react";
import { useParams, useHistory } from "react-router";
const EditBanner = (props) => {
const [imgValue, setImgValue] = useState('');
const [descriptionValue, setDescriptionValue] = useState('');
const params = useParams();
const history = useHistory();
const imgRef = useRef();
const descriptionRef = useRef();
useEffect(() => {
const fetchBlog = async () => {
const response = await fetch(`URL/banners/${params.id}.json`);
const data = await response.json();
setImgValue(data.img);
setDescriptionValue(data.description);
}
fetchBlog();
},[params])
const onSubmitHandler = (e) => {
e.preventDefault()
fetch(`URL/banners/${params.id}.json`,{
method: "PUT",
body: JSON.stringify({
description: descriptionRef.current.value,
img: imgRef.current.value
}),
headers: {
'Content-Type': 'application/json'
}
})
history.push(`/banners/${params.id}`);
}
const imgUrlChangeHandler = () => {
setImgValue(imgRef.current.value)
}
const descriptionChangeHandler = () => {
setDescriptionValue(descriptionRef.current.value)
}
return (
<form onSubmit={onSubmitHandler}>
<input type="text" placeholder="img url" ref={imgRef} value={imgValue} onChange={imgUrlChangeHandler}></input>
<textarea ref={descriptionRef} value={descriptionValue} onChange={descriptionChangeHandler}></textarea>
<button>Submit</button>
</form>
)
}
export default EditBanner;
这里是我用useHistory()钩子重定向到的Detail页面。记住如果我把bannerDetail作为一个依赖项添加到useEffect钩子中它会起作用但之后我将创建一个无限循环
import { useEffect, useState } from 'react';
import { useParams } from 'react-router';
import { useHistory } from 'react-router';
import styles from './BannerDetail.module.css';
const BannerDetail = (props) => {
const history = useHistory();
const params = useParams();
const [bannerDetail, setBannerDetail] = useState({});
useEffect(() => {
const fetchBanner = async () => {
const response = await fetch(`URL/banners/${params.id}.json`);
const data = await response.json();
console.log(data)
setBannerDetail(data);
}
console.log('useEffect run in bannerDetail')
fetchBanner();
},[params])
const onEditHandler = (e) => {
e.preventDefault();
history.push(`/banners/${params.id}/edit`)
}
const onDeleteHandler = (e) => {
e.preventDefault();
fetch(`URL/banners/${params.id}.json`,{
method: "DELETE",
headers: {
'Content-Type': 'application/json'
}
})
history.replace('/banners')
}
return (
<section className={styles.detail}>
<div className={styles['image-container']}>
<img
src={bannerDetail.img}
alt={bannerDetail.description}
/>
</div>
<div className={styles['description-container']}>
<p>{bannerDetail.description}</p>
</div>
<div className={styles.actions}>
<button onClick={onEditHandler}>Edit</button>
<button onClick={onDeleteHandler}>Delete</button>
</div>
</section>
)
}
export default BannerDetail;
这里还有我所有的路由,
<Switch>
<Route path="/" exact><Redirect to="/banners"/></Route>
<Route path="/banners" exact> <Banners/> </Route>
<Route path="/new-banner" exact>
<AddNewUser/>
</Route>
<Route path="/banners/:id/edit" exact>
<EditBanner/>
</Route>
<Route path="/banners/:id" >
<BannerDetail/>
</Route>
</Switch>
我认为您遇到的问题是,您正在调度一个PUT请求,然后在组件挂载时立即导航到新页面,其中发出GET请求。网络请求解析的顺序没有保证。
您可能希望在导航到下一页之前先等待PUT请求解析。
const onSubmitHandler = (e) => {
e.preventDefault();
fetch(`URL/banners/${params.id}.json`,{
method: "PUT",
body: JSON.stringify({
description: descriptionRef.current.value,
img: imgRef.current.value
}),
headers: {
'Content-Type': 'application/json'
}
}).finally(() => {
// regardless of fetch resolve/reject, navigate to new page
history.push(`/banners/${params.id}`);
});
}
也许在这里,虽然你可能只想导航到下一页,如果fetch
解析,或者只有200OK的响应,或者你有什么,使用.then
块。也许你想处理被拒绝的响应以向用户显示错误消息,请使用.catch
块。
const onSubmitHandler = (e) => {
e.preventDefault();
fetch(`URL/banners/${params.id}.json`,{
method: "PUT",
body: JSON.stringify({
description: descriptionRef.current.value,
img: imgRef.current.value
}),
headers: {
'Content-Type': 'application/json'
}
})
.then((response) => {
if (response.ok) throw new Error('response not ok');
history.push(`/banners/${params.id}`);
})
.catch(error => {
// handle errors
});
}
如果您更喜欢async/await
而不是Promise链:
const onSubmitHandler = async (e) => {
e.preventDefault();
try {
const response = await fetch(`URL/banners/${params.id}.json`,{
method: "PUT",
body: JSON.stringify({
description: descriptionRef.current.value,
img: imgRef.current.value
}),
headers: {
'Content-Type': 'application/json'
}
});
if (response.ok) throw new Error('response not ok');
history.push(`/banners/${params.id}`);
} catch(error) {
// handle errors
}
}