【发布时间】:2017-07-31 22:55:19
【问题描述】:
我正在使用 reducer 来检查各种操作状态,如成功、待处理、错误等。我想在延迟 1 秒后显示加载指示器。如果响应在 1 秒之前出现,那么我不想显示加载指示器。
目前,我没有更新挂起状态的加载状态,而是使用 setTimeout 从渲染函数触发操作。
这会在超时期限之前交付响应时产生问题。我该如何解决这个问题?
reducer.js:
const initialState = {
error: false,
loading: false,
showModal: false,
};
export default function appReducer(state=initialState, action) {
if (action.type.endsWith('ERROR'))
return {
...state,
error: true,
loading: false,
showModal: true,
};
else if (action.type.endsWith('PENDING'))
return {
...state,
error: false,
loading: false,
};
else if (action.type.endsWith('SUCCESS'))
return {
...state,
error: false,
loading: false,
};
else if (action.type === errorModalActionTypes.CLOSE_MODAL.ACTION)
return {
...state,
showModal: false,
};
else if (action.type === loadingIndicatorActionTypes.UPDATE_LOADING.ACTION)
return {
...state,
loading: true,
};
else
return state;
}
saga.js
export function* getCollections(action) {
try {
yield put({ type: GET_COLLECTIONS.PENDING });
const collections = yield call(getCollectionsAPI);
yield put({ type: GET_COLLECTIONS.SUCCESS, collections });
} catch (error) {
yield put({ type: GET_COLLECTIONS.ERROR, error });
}
}
// These are the watchers that trigger the start of a saga
export default function* saga() {
yield fork(takeEvery, GET_COLLECTIONS.ACTION, getCollections);
}
LoadingIndicator.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { isLoading, hasError } from './selectors';
import { updateLoading } from './actions';
import LoadingIndicatorComponent from '../../../../components/loadingIndicator';
import './loadingIndicator.css';
export class LoadingIndicator extends Component {
render() {
console.log('called');
const { loading, error } = this.props;
if (!error)
setTimeout(this.props.updateLoading, 1000);
return (
<div className={`${loading && !error ? 'show' : 'hidden'}`}>
<LoadingIndicatorComponent>
Loading...
</LoadingIndicatorComponent>
</div>
);
}
}
const mapStateToProps = (state) => ({
loading: isLoading(state),
error: hasError(state),
});
export default connect(mapStateToProps, { updateLoading })(LoadingIndicator);
【问题讨论】:
标签: javascript reactjs redux react-redux redux-saga