确保我的反应应用程序具有使用反应路由器时所需的所有数据的最佳方法是什么?基本上我想获取一些在整个应用程序中使用的基本数据,问题是,当我这样做时,“简单的方法”我的一些数据被提取两次。
当我输入索引路径(Dashboard)时,它首先挂载此组件并触发this.props.fetchAllProjects()
,而不是挂载Loader组件并触发this.props.fetchUsersInfo()
,因此它只显示Spinner组件并且在获取用户信息数据之后再次挂载仪表板和火this.props.fetchAllProjects()
有什么好办法吗?
这是我目前的代码:
AppRouter.jsx
<Router history={browserHistory}>
<Route component={Loader}>
<Route path="/" component={MainLayout}>
<IndexRoute components={{ rightSidebar: RightSidebar, main: Dashboard }} />
<Route path="accounts" components={{ rightSidebar: RightSidebar, main: Accounts }} />
</Route>
</Route>
<Route path="*" component={PageNotFound} />
Loader.jsx
import React from 'react';
import { connect } from 'react-redux';
import { fetchUsersInfo } from 'actions/index.actions';
import Spinner from 'components/spinner/Spinner.component';
class Loader extends React.Component {
componentDidMount() {
this.props.fetchUsersInfo();
}
render() {
return (
<div>
{this.props.appState.isFetchingUsersInfo ?
<div>
<Spinner />
</div>
:
<div>
{this.props.children}
</div>
}
</div>
);
}
}
Loader.propTypes = {
children: React.PropTypes.node.isRequired,
appState: React.PropTypes.shape({
isFetchingUsersInfo: React.PropTypes.bool.isRequired,
}),
fetchUsersInfo: React.PropTypes.func.isRequired,
};
const mapStateToProps = state => ({
appState: {
isFetchingUsersInfo: state.appState.isFetchingUsersInfo,
},
});
export default connect(mapStateToProps, { fetchUsersInfo })(Loader);
Dashboard.jsx
import React from 'react';
import { connect } from 'react-redux';
import { fetchAllProjects } from 'actions/index.actions';
import styles from './Dashboard.container.scss';
class Dashboard extends React.Component {
componentDidMount() {
this.props.fetchAllProjects();
}
render() {
return (
<div>
Dashboard
</div>
);
}
}
Dashboard.propTypes = {
appState: React.PropTypes.shape({
isFetchingProjects: React.PropTypes.bool.isRequired,
}),
fetchAllProjects: React.PropTypes.func.isRequired,
};
const mapStateToProps = state => ({
appState: {
isFetchingProjects: state.appState.isFetchingProjects,
},
});
export default connect(mapStateToProps, { fetchAllProjects })(Dashboard);