如何在POST请求完成后点击按钮刷新React页面/组件及数据表格
Got it, let's get this sorted! You want your table to refresh right after the POST request finishes successfully—here's how to adjust your code to make that happen smoothly.
Step 1: Update Your click Async Function
The key is to call your refreshPage function only after the POST request succeeds, and add error handling to avoid refreshing if something goes wrong. Here's the modified code:
async click() { const { domainInputValue } = this.state; console.log(domainInputValue); try { const response = await fetch('/new-cert', { headers: { 'Content-Type': 'application/json' }, method: 'POST', body: JSON.stringify({ domain: domainInputValue }) // Fill in your full request body here }); // Verify the request actually succeeded (status code 2xx) if (!response.ok) { throw new Error(`Request failed with status: ${response.status}`); } // Trigger table refresh once POST is confirmed successful await this.refreshPage(); // Optional: Clear the input field for better user experience this.setState({ domainInputValue: '' }); } catch (error) { console.error('Failed to add new certificate:', error); // Optional: Show a user-friendly error message // this.setState({ errorMsg: 'Could not add domain. Please try again.' }); } }
Step 2: Ensure refreshPage Updates Your Table Data
Assuming refreshPage is meant to reload your table's data (instead of reloading the entire page), here's an example of what that function might look like if it's not already implemented:
async refreshPage() { // Fetch the updated list of certificates from your backend const response = await fetch('/cert-list'); // Replace with your table data endpoint const updatedTableData = await response.json(); // Update component state to trigger table re-render with fresh data this.setState({ tableData: updatedTableData }); }
Why This Works
- Error Safety: The
try/catchblock prevents table refreshes when the POST request fails (e.g., network issues, server errors). - Success Validation: Checking
response.okconfirms the server accepted the request before refreshing, so you don't show stale or incorrect data. - UX Improvements: Clearing the input field after success makes it easier for users to add another domain without manual cleanup.
If you specifically need to reload the entire page instead of just the component, you can replace await this.refreshPage() with window.location.reload()—but in React, updating the component's state (like the example above) is the cleaner, more performant approach.
内容的提问来源于stack exchange,提问作者tnoel999888

