import React,{Component,} from 'react';
import {Route,Redirect} from 'react-router-dom';
export default class PrivateRoute extends React.Component{
constructor(){
super()
}
render(){
const {component, authed, ...rest}=this.props;
return(
<Route
{...rest}
render={(props) => authed === true
? <Component {...this.props} />
: <Redirect to={{pathname: '/login', state: {from: props.location}}} />} />
)
}
}
错误:ReactComponent(...):在返回的组件实例上找不到render
方法:您可能忘记定义render
。
答案 0 :(得分:0)
您不能在渲染方法中使用Component
作为输出,需要创建扩展它的类。:
创建TestComponent
import React from 'react';
import {Route, Redirect} from 'react-router-dom';
export default class TestComponent extends React.Component{
render(){
return <span>Hello</span>
}
}
<强> PrivateRoute 强>
请注意,我已删除constructor
,因为此处不需要:
import React from 'react';
import {Route, Redirect} from 'react-router-dom';
import TestComponent from './TestComponent';
export default class PrivateRoute extends React.Component{
render(){
const {component, authed, ...rest}=this.props;
return(
<Route
{...rest}
render={(props) => authed === true
? <TestComponent {...this.props} />
: <Redirect to={{pathname: '/login', state: {from: props.location}}} />} />
)
}
}