【发布时间】:2018-05-09 11:24:10
【问题描述】:
我正在写LoadingComponent,它应该在加载一些数据时返回Spinner,完成后它应该返回this.props.children。
我在componentWillMount获取数据:
class LoadingComponent extends React.Component {
componentWillMount() {
this.props.userActions.onUserAuthChange();
this.props.currencyActions.getCurrencies();
}
}
我检查是否正在加载用户或货币之一,如果是,则返回 Spinner:
render() {
const {loadingUser, loadingCurrencies} = this.props;
if (loadingCurrencies || loadingUser) {
return (
<Spinner/>
)
}
return (
this.props.children
)
}
这是我将state 连接到props 的地方:
const mapStateToProps = state => ({
user: state.user,
loadingUser: state.loading.loadingUser,
loadingCurrencies: state.loading.loadingCurrencies,
});
const mapDispatchToProps = dispatch => ({
userActions: bindActionCreators(userActions, dispatch),
currencyActions: bindActionCreators(currencyActions, dispatch),
});
const ConnectedLoading = connect(mapStateToProps, mapDispatchToProps)
(LoadingComponent);
export default withRouter(ConnectedLoading);
还有loadingReducer:
const loadingReducer = (state = initialState.loading, action) => {
switch (action.type) {
case actionTypes.LOADING:
return {...state, isLoading: action.loading};
case actionTypes.LOADING_USER:
return {...state, loadingUser: action.loadingUser};
case actionTypes.LOADING_CURRENCIES:
return {...state, loadingCurrencies: action.loadingCurrencies};
default:
return state;
}
};
问题是loadingUser 和loadingCurrencies 总是错误的。这是getCurrencies 函数,它在数据开始下载时以 true 调度,之后以 false 调度:
export const getCurrencies = () => async dispatch => {
try {
dispatch(loadingCurrencies(true));
const currencies = await get();
dispatch(loadCurrencies(currencies.rates));
dispatch(loadingCurrencies(false));
} catch (e) {
}
}
我在 App.js 中使用 LoadingComponent:
render() {
return (
<LoadingComponent>
<div className='App'>
<Route path='/:lang' render={props =>
languages.hasOwnProperty(props.match.params.lang) ?
<Navbar {...props}/> :
<Redirect to={`/${defaultLanguage}`}/>}
/>
<Layout/>
</div>
</LoadingComponent>
)
}
这是监听loadCurrencies(currencies.rates)的reducer函数:
const currencyReducer = (state = initialState.currency, action) => {
switch (action.type) {
case actionTypes.LOAD_CURRENCIES:
return {...state, currencies: action.currencies};
case actionTypes.CHANGE_CURRENCY:
return {...state, current: action.current};
default:
return state;
}
}
在调试过程中注意到LoadingComponent Redux 开发工具未激活,它开始在LoadingComponent 的孩子处激活。实际上,当我在 reducer 处设置断点时,状态会发生变化......在 Redux Dev Tool 开始处于活动状态后,我可以观察到加载状态实际上已更改为 false -> true -> false。如果有人可以提供帮助,我将不胜感激。
【问题讨论】:
-
可以发一下收听
loadCurrencies(currencies.rates)的reducer吗? -
通过
connect()将加载组件连接到商店的部分在哪里? -
当你的空鱼被捕获时会发生什么?您应该删除整个 try/catch 包装器
标签: reactjs redux react-router react-redux