我正在尝试进行经过身份验证的路由,问题是当化简值loggedIn
更改时(登录组件中触发)我的根组件没有更新。结果,authed
的道具PrivateRoute
也没有更新
根:
import React, { Component } from "react";
import { Provider } from "react-redux";
// import { BrowserRouter, Route, browserHistory, Switch } from "react-router";
import { HashRouter as Router, Route, Switch, Redirect} from "react-router-dom";
import { hot } from 'react-hot-loader'
import { ConnectedRouter } from 'connected-react-router'
import configureStore, {history} from '../store/configureStore'
import App from "./App";
import Startpage from "./startpage";
import PatientSearch from "./routes/patient/patientSearch";
import Technician from "./routes/technician/technician";
import Notes from "./routes/notes/notes";
import DeliveryReports from './routes/admin/deliveryReports/reports'
import Analytics from './routes/admin/analytics/analytics'
import {connect} from 'react-redux'
import * as actions from "../actions";
import Login from './login';
import Cookies from "cookies-js";
const store = configureStore(/* provide initial state if any */)
const PrivateRoute = ({ component: Component, authed, ...rest }) => (
<Route {...rest} render={(props) => (
authed === true
? <Component {...props} />
: <Redirect to={{
pathname: '/login',
state: { from: props }
}} />
)} />
)
class Root extends Component {
state = {loggedIn:false}
componentWillMount() {
this.props.dispatch(actions.isLoggedIn())
console.log('hellOOOO')
this.checkCookie()
}
componentDidUpdate(prevProps) {
console.log('rootprops', this.props.loggedIn, prevProps.loggedIn)
this.props.loggedIn!==prevProps.loggedIn&&this.setState({loggedIn:this.props.loggedIn})
}
render() {
console.log('propsroot', this.state.loggedIn)
return (
<Provider store={store}>
<ConnectedRouter history={history}>
<Router >
<App>
<Switch>
<PrivateRoute exact path="/" authed={this.state.loggedIn} component={Startpage} />
<Route
component={PatientSearch}
path="/patient/search"
/>
<PrivateRoute
component={Technician}
path="/technician"
authed={this.state.loggedIn}
/>
<Route
component={Login}
path="/login"
/>
<Route
component={Analytics}
path="/analytics"
/>
<Route
component={Notes}
path="/notes"
/>
<Route
component={DeliveryReports}
path="/delivery_reports"
/>
</Switch>
</App>
</Router>
</ConnectedRouter>
</Provider>
);
}
}
const mapStateToProps=(state)=>{
return {
loggedIn: state.app.loggedIn,
token: state.app.token,
};
}
export default connect(mapStateToProps)(hot(module)(Root))
即使已分派操作并且更改了loginIn的值,也不会触发ComponentDidUpdate。
减速器部分:
case "SIGN_IN":
return {
...state,
loggedIn:true,
errors:''}
编辑:将Routes移至App组件,并且在那里一切正常。但是,我遇到另一个问题:当我第一次重新加载或加载Web应用程序时,它会重定向到Login
组件。日志显示loggedIn
最初是假的,但后来变成了真,但是无论如何都未渲染组件(猜测authed
尚未更新)