你好,如果没有验证,但我尝试保护路由
警告:您不应在同一路径中使用Route组件和Route渲染;路线渲染将被忽略
App.js
import React, { Fragment, useEffect } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import NavBar from './component/Layout/NavBar';
import Landing from './component/Layout/Landing';
import Login from '../src/component/Auth/Login';
import Register from '../src/component/Auth/Register';
import Dashboard from './component/dashboard/Dashboard';
import Alert from './component/Auth/Alert';
import PrivateRoute from './component/routing/PrivateRoute';
import './App.css';
// Redux
import { Provider } from 'react-redux';
import store from './store';
import setAuthToken from './utils/token';
import { loadUser } from './action/auth';
if (localStorage.token) {
setAuthToken(localStorage.token);
}
const App = () => {
useEffect(() => {
store.dispatch(
loadUser());
}, []);
return (
<Provider store={store}>
<Router>
<Fragment>
<NavBar />
<Route exact path="/" component={Landing}></Route>
<section className="container">
<Alert />
<Switch>
<Route exact path="/login" component={Login}></Route>
<Route exact path="/register" component={Register}></Route>
<PrivateRoute exact path="/dashboard" component={Dashboard}></PrivateRoute>
</Switch>
</section>
</Fragment>
</Router>
</Provider>
);
};
export default App;
PrivateRoute.js
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Route, Redirect } from 'react-router-dom';
const PrivateRoute = ({
componet: Component,
auth: { isAuthenticated, loading },
...rest
}) => (
<Route
{...rest}
render={props =>
!isAuthenticated && !loading ? (
<Redirect to="/login" />
) : (
<Component {...props} />
)
}
/>
);
PrivateRoute.propTypes = {
auth: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
auth: state.auth
});
export default connect(mapStateToProps)(PrivateRoute);
警告:您不应在同一路线中使用“路线组件”和“路线渲染”; “路线渲染”将被忽略
我该如何解决?
答案 0 :(得分:1)
使用<Route render={() => <YourComponent />} />
代替<Route component={YourComponent} />
。
不要将其中两个结合在一起,react不会那样。
答案 1 :(得分:1)
使用
<Route>
渲染内容的方式有3种:- <Route component> - <Route render> - <Route children>
每种在不同情况下都是有用的。您应该在给定
上仅仅使用这些道具之一
PrivateRoute
包含component
和render
道具。您只能使用一种渲染方法,但不能同时使用。
<PrivateRoute exact path="/dashboard" component={Dashboard}></PrivateRoute> // here
const PrivateRoute = ({
...
}) => (
<Route
render={props => ()} // here
/>
);
FIX
:将component
道具重命名为comp
,因为它是HOC:
// rename prop to `comp`
<PrivateRoute exact path="/dashboard" comp={Dashboard}></PrivateRoute>
const PrivateRoute = ({
comp: Component, // use comp prop
auth: { isAuthenticated, loading },
...rest
}) => (
<Route
{...rest}
render={props =>
!isAuthenticated && !loading ? (
<Redirect to="/login" />
) : (
<Component {...props} />
)
}
/>
);