React中useHistory重定向后目标组件数据未更新的问题解决方案咨询
Let's break down why this is happening and fix it step by step:
1. The Async Order Issue
Right now, you're calling updateNotes() and immediately doing history.push('/notes')—but updateNotes() is asynchronous. That means the redirect happens before your API update request finishes, so the Notes component loads the old data before the new data is even saved.
Fix the Submit Handler & Update Function
First, we need to wait for the update request to complete before redirecting. Here's how to adjust your code:
Update the submitHandler to wait for updateNotes() to finish:
const submitHandler = (e) => { e.preventDefault(); Swal.fire({ title: 'Are you sure?', showDenyButton: true, showCancelButton: true, confirmButtonText: `Yes`, denyButtonText: `No`, }).then(async (result) => { // Add async here if (result.isConfirmed) { try { await updateNotes(); // Wait for the update to finish history.push('/notes'); } catch (err) { // Error is already handled in updateNotes, no extra action needed here } } else if (result.isDenied) { Swal.fire('Notes not updated!', '', 'info'); } }); };
Then, modify updateNotes() to return the promise so await works properly:
async function updateNotes() { bodyFormData.append('description', notesData.description); const requestOptions = { method: 'PUT', headers: { Authorization: AuthStr }, body: bodyFormData, }; // Return the fetch promise so we can await it return fetch(URL, requestOptions) .then(async (response) => { const data = await response.json(); if (!response.ok) { const error = (data && data.message) || response.status; return Promise.reject(error); } Swal.fire('Notes updated successfully', '', 'success'); }) .catch((error) => { Swal.fire('Error updating notes', '', 'error'); throw error; // Re-throw to let the submitHandler catch failures }); }
2. Force Notes Component to Refresh on Redirect
Even if we wait for the update to finish, the Notes component only fetches data when fetchURL changes. When you redirect back to /notes, we need to trigger a fresh data fetch whenever the route changes.
Update the Notes Component's useEffect
Add useLocation to listen for route changes, and include it in the useEffect dependencies:
First, import it:
import { useLocation } from 'react-router-dom';
Then use it in your component:
const NotesComponent = () => { const location = useLocation(); // Get current route location // ... your existing state (notes, next, etc.) useEffect(() => { axios .get(fetchURL, { headers: { Authorization: AuthStr } }) .then((response) => { if (response) { if (!response.data[response.data.length - 1].has_next) setNext(0); setNotes(response.data); } }) .catch((error) => { toast.error('Something went wrong, please refresh'); console.log(error); }); }, [fetchURL, location]); // Add location as a dependency // ... rest of your component code };
This way, every time the route changes (like when you redirect from the update page to /notes), the useEffect will re-run and fetch the latest data from your API.
Why This Works
- By awaiting
updateNotes(), we ensure the API update is fully completed before sending the user to the Notes page. - Adding
locationto the useEffect dependencies tells React to re-fetch data whenever the route changes, guaranteeing the component always shows the most up-to-date content.
内容的提问来源于stack exchange,提问作者Usurper

