React 14.3中fetchData执行后如何设置loading状态为false?
Hey there! Let's get that loading state sorted out. Since you're using React 14.3 (which doesn't support async/await yet), we'll lean on native Promise methods to make sure all three API calls finish before flipping the loading switch off.
Step 1: Update your fetchData function to handle all Promises together
First, wrap your three API calls in Promise.all()—this method waits for every Promise in the list to resolve (or catches the first one that rejects). Make sure to return the Promise chain so you can hook into it later:
fetchData() { // Replace these with your actual API call Promises const apiCall1 = fetch('/api/first-endpoint').then(res => res.json()); const apiCall2 = fetch('/api/second-endpoint').then(res => res.json()); const apiCall3 = fetch('/api/third-endpoint').then(res => res.json()); // Wait for all three calls to complete return Promise.all([apiCall1, apiCall2, apiCall3]) .then(([dataFromCall1, dataFromCall2, dataFromCall3]) => { // Store the returned data in state (adjust this to your needs) this.setState({ data1: dataFromCall1, data2: dataFromCall2, data3: dataFromCall3 }); }) .catch(error => { // Don't forget error handling! console.error('Oops, one of the API calls failed:', error); this.setState({ errorMessage: 'Failed to load data' }); }); }
Step 2: Trigger loading state cleanup after fetchData finishes
In your componentWillMount, after starting fetchData, chain a method to set loading to false—this should run no matter if the calls succeeded or failed to avoid a stuck loading state:
Option 1: Using Promise.finally() (if your environment supports it)
componentWillMount() { this.setState({ loading: true }); this.fetchData() .finally(() => { // This runs whether the calls succeeded or failed this.setState({ loading: false }); }); }
Option 2: Fallback for older environments without finally
componentWillMount() { this.setState({ loading: true }); this.fetchData() .then(() => this.setState({ loading: false })) .catch(() => this.setState({ loading: false })); }
A quick breakdown of why this works
Promise.all()ensures we don't turn off loading until all three API calls are done—no more setting loading to false halfway through!- By returning the Promise chain from
fetchData, we can listen for when the entire operation finishes incomponentWillMount. - Handling both success and failure cases means your loading state won't get stuck if one of the API calls fails.
Just a heads up: In newer React versions, componentWillMount is considered unsafe, but since you're on 14.3, you're good to use it here.
内容的提问来源于stack exchange,提问作者Azad Rahman

