我在Redux上使用React。经过身份验证时,即this.props.isAuthenticated = true时,不会呈现/ add,而是呈现/路由。但是,如果我将/ add移出this.props.isAuthenticated条件,它将被呈现。我不知道为什么会这样。
App.js
import React, { Component } from 'react';
import { Route, Switch, withRouter, Redirect, Link} from 'react-router-dom';
import { connect } from 'react-redux';
import './App.css';
import asyncComponent from './hoc/asyncComponent/asyncComponent';
import * as action from './store/actions/index';
const asyncSignUp = asyncComponent(() => {
return import('./containers/Signup/Signup');
})
const aysncLogin = asyncComponent(() => {
return import('./containers/Login/Login');
})
const asyncAddStore = asyncComponent(() => {
return import ('./containers/Add/Add');
})
const asyncGetHome = asyncComponent(() => {
return import ('./containers/Home/Home');
})
class App extends Component {
componentDidMount() {
this.props.onTryAutoLogin();
}
render(){
let route = (
<Switch>
<Route path="/signup" component={asyncSignUp} />
<Route path="/login" component={aysncLogin} />
<Redirect to="/"/>
</Switch>
);
if(this.props.isAuthenticated){
route = (
<Switch>
<Route path="/add" component={asyncAddStore} />
<Route path="/" exact component={asyncGetHome}/>
<Redirect to="/"/>
</Switch>
);
}
return (
<div className="App">
<header className="App-header">
{route}
</header>
</div>
);
}
}
const mapStateToProps = state => {
return {
isAuthenticated: state.auth.token !== null,
userData: state.auth.data
};
};
const mapDispatchToProps = dispatch => {
return {
onTryAutoLogin: () => dispatch(action.authCheckState())
};
};
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App));
authComponent.js
import React, { Component } from 'react';
const asyncComponent = (importComponent) => {
return class extends Component {
state = {
component: null
};
componentDidMount(){
importComponent().then(cmp => {
this.setState({component: cmp.default});
});
}
render(){
const C = this.state.component;
return C ? <C {...this.props}/> : null;
}
}
}
export default asyncComponent;
答案 0 :(得分:0)
您有<Route path="/add" component={asyncAddStore} />
,但您声明了const asyncAdd = ...
。我假设asyncAdd
应该是asyncAddStore
?
基于这个假设,我认为您的问题可能不在您提供的文件之外:
确保您的<Switch>
组件位于<Router>
(或<BrowserRouter>
组件)中...您的父级中可能有一个您的App.js
还要确保呈现您的App组件(您需要将<Switch>
包裹在上面的<Router>
中)或重新呈现<App>
的父组件,像这样...
ReactDOM.render(