问题描述:

Let's say my app is a list of many items. There's a lot of items so I don't want to include all the items in the redux state.

When a user visits me at myapp.com/item/:itemId, I want to display the selected item. Currently I make an api call in componentDidMount to fetch the item and store the response in myReduxState.selectedItem. However, this shows the user and unfinished page until the api call finishes.

Is there any way I can get around this?

网友答案:

The pattern I tend to follow is to have a state of fetching being tracked in the redux state. Once the api resolves you just make sure the state is set correctly and then in your render methods use that to determine what you are rendering.

render() {
 if (this.state.fetching) { 

  return <div> // put whatever you want here, maybe a loading component?</div>

 }

 return ( 
   // put the regular content you would put for when the api call finishes and have the data you need
 )
}
网友答案:

I solved this problem by making the creating the state on the server side. I get the itemId from the url in my express route and get the details of the specific item. I use this to create the state and pass it to the front-end.

相关阅读:
Top