[英]How to make a single loader reducer for whole application, React
I have an application in which I have multiple components as well as actions and reducers for each component. 我有一个应用程序,其中有多个组件以及每个组件的动作和简化器。 I am using redux-pack for promise handling as well. 我也在使用redux-pack进行承诺处理。
So here is the situation, I just want to use a single reducer for my whole application which handles my page-loader. 因此,在这种情况下,我只想对处理页面加载程序的整个应用程序使用单个reducer。 That means, whenever an API call start, the loader should show and it should hide when the API ends. 这意味着,每当API调用开始时,加载器应显示,并且在API结束时应隐藏。 I don't want to write a separate action for this. 我不想为此写一个单独的动作。
Please help me with your suggestions. 请给我您的建议。 Thanks in advance. 提前致谢。
, I don't have the proper idea redux-pack
but I have achieved this using react-redux
. ,我没有适当的想法redux-pack
但是我已经使用react-redux
实现了。 There is library react-loading-overlay
library you can use it or create a new loading-overlay
own. 有一个库react-loading-overlay
库,您可以使用它或自己创建一个新的loading-overlay
。
https://github.com/derrickpelletier/react-loading-overlay Link of the library if you want. https://github.com/derrickpelletier/react-loading-overlay如果需要的话,链接库。
Now coming to the code:- 现在来看代码:
I have created a global state in redux named as loadingState
我在redux中创建了一个名为loadingState
的全局状态
//this is my action.
export const ENABLE_OR_DISABLE_LOADING = 'ENABLE_OR_DISABLE_LOADING';
export function enableOrDisableLoading (value = true, msg='Loading your content') {
return {
type: ENABLE_OR_DISABLE_LOADING,
payload: {isLoading: value, msg: msg}
};
}
//this is my reducer.
export function loading(state={isLoading: false, msg: 'Please wait...'}, action) {
switch (action.type) {
case ENABLE_OR_DISABLE_LOADING:
return action.payload;
default:
return state;
}
}
Add this reducer to your store.
My HOC is like this.
import LoadingOverlayWrapper from 'react-loading-overlay';
class AdminImpl extends React.Component {
return (
<LoadingOverlayWrapper
active={this.props.isLoading}
spinner
zIndex={1000}
className="height100"
text={this.props.msg}
>
<SideBar/>
{this.props.child}
</LoadingOverlayWrapper>
);
}
const mapStateToProps = (state) => {
return state.loading;
};
export const Admin = connect(mapStateToProps)(AdminImpl);
Now dispatch action from anywhere from your app.
//start Loading state
store.dispatch(enableOrDisableLoading(true, 'Your loading msg'));
//start Loading state
store.dispatch(enableOrDisableLoading(false));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.