tim*_*ods 6 javascript reactjs redux react-redux axios
In my react application, a user logs in and then directed to his/her dashboard upon authentication. In order to display all the data of the user in the dashboard I have a separate file in which there is a function called getUserData() which dispatches all the actions of the dashboard components and then getUserData() is called within loadUser() so every time the app renders it excutes loadUser(). Is this a good practice and an efficient way to display user data as the app grows larger? Or is there a better way to do it and if so, I would love to know about it. Thank you.
//App.js
const token = localStorage.getItem('token')
store.dispatch({type: USER_LOADING});
if(token){
store.dispatch({type: USER_AUTHENTICATED})
}
class App extends Component{
componentDidMount(){
store.dispatch(loadUser());
}
render(){
return(
<Provider store={store}>
<div className="App">
<Router>
<Switch>
<Route exact path="/login" component={LoginPage}/>
<ProtectedRoute exact path="/dashboard" component={Dashboard}/>
</Switch>
</Router>
</div>
</Provider>
);
}
};
export default App;
Run Code Online (Sandbox Code Playgroud)
//Load user
export const loadUser = () => (dispatch, getState) =>{
//dispatch(getNetworkList(config))
axios.get('/api/user/', setAuthorizationHeader(getState))
.then(res => {
dispatch({
type: USER_LOADED,
payload: res.data
})
dispatch(getUserData())
})
.catch(err => {
dispatch(returnErrors(err.response.data, err.response.status));
dispatch({
type: AUTH_ERROR
});
});
};
Run Code Online (Sandbox Code Playgroud)
//Get user data
export const getUserData = () =>(dispatch) =>{
dispatch(userProfile())
dispatch(getComments())
dispatch(getInvites())
dispatch(getNotifications())
dispatch(getMessages())
dispatch(getProjects())
dispatch(getConnections())
dispatch(getReply())
dispatch(getPendingRequests())
dispatch(getAssignedTasks())
};
Run Code Online (Sandbox Code Playgroud)
我建议您应用所谓的延迟加载...因此,如果 userProfile 是加载仪表板时的活动选项卡,则您userProfile仅分派操作...并触发其余操作onRelatedTabMounted
因为最有可能的是,用户将针对特定信息(评论、邀请等)...因此无需在仪表板加载上获取所有信息...
| 归档时间: |
|
| 查看次数: |
89 次 |
| 最近记录: |