React router 4自定义组件给出渲染功能错误

时间:2017-11-07 11:43:11

标签: reactjs react-router

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

1 个答案:

答案 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}}} />} />
        )
    }
}