简体   繁体   中英

Best way to clear redux state

I have question about clearing redux state. I have state named search for searching address with fetching. It's structure like this

search:{
  status: 'INIT',
  results: [],
}

status is a flag for async request something like 'SUCCESS' or 'FAILURE'.

results is a result of fetching.

When user search address with some search word, results has result of fetching. And My component render like this,

<div>
   {this.props.results.map((result,i)=>{
     <div>{result}</div>
   )}
</div>

So my problem is when user try to search again after some other works, component render previous search result because results is not clear.

Currently, I dispatch action 'CLEAR_SEARCH' that initialize search state, after works using results has done. But i think it's not a good way.

Is there any better idea?

When you start initialising the new request, you can dispatch an action call START_LOADING

 dispatch(startLoadingAction())
 try {
     const result = await fetch...
     dispatch(successAction(result));
 } catch {
     dispatch(failureAction());
 }

then handle it like this:

 case START_LOADING:
     state = {
         status: 'LOADING',
         result: [],
     };
     break;

一种常见的模式是让{ isLoading: false, data: [], error: false, isLoaded: true, hasFailed: false, }请求看起来更像{ isLoading: false, data: [], error: false, isLoaded: true, hasFailed: false, }以便当您清除或重新发出搜索结果时,状态为请求发生变化,您可以根据请求进行显示,而不仅仅是显示数据。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM