React-redux asynchronously reads data

  node.js, question

I tried to write a Blog system of react and redux. The back end was built by express. I mainly completed some additions, deletions and changes. I encountered such a situation when getting data at the front end.

Not considered in the early stage, it passed at the beginning of page loading:

Store.dispatch (getallarticle ())//use request to request articles from the background and update store
 Store.dispatch (getallcategory ())//use request to request the classification list from the background and update the store
 ReactDOM.render(
 <Provider store={store}>
 <div>
 <Router history={history} routes={AppRoutes} onUpdate={() => window.scrollTo(0,0)} />
 </div>
 </Provider>,document.getElementById('app')
 )

Get articles and categories, save the results in store, and give the components through Provider.

Subsequently, the category variable in store is bound to the component through mapStateToProps in the category component. When using, it is found that category has been read three times, the first two times are empty, and the third time is correct, as shown in the figure:

图片描述

It was discovered that the two dispatch before the page was loaded were the cause.

Think of a solution:

  1. Prepare toStore.dispatch(getAllArticle ()), store.dispatch(getAllCategory ()), and ReactDOM.renderPut it into the Generator function and execute it in turn.

  2. The store always adds an isLoading field. each component judges the status of isLoading and then renders the component’s this.props.article and this.props.category into the page.

  3. Put the view that needs to render the state.article into the componentWillReceiveProps method, and re-render each time this.props.article and this.props.category update.

Is there any better way?

Isn’t it quite normal? What’s the problem with the first two vacancies? Before the data is obtained, it is good to display the interface accordingly.

Your solution:
1 is not necessary, the data didn’t get the money, the interface can’t display at all;
2 It is necessary to display it according to the loading status.
3 No need, unless the obtained data needs to be cached in the state, it is usually in different formats and does not want to incur too much overhead in the render before doing so. Otherwise, there is no need to reinvent the wheel and just take it directly from props (inject it with react-redux connect).