React中的PrivateRouter组件

时间:2019-05-20 19:53:39

标签: javascript reactjs react-redux

我正在使用专用路由器功能组件,并且想将其转换为类组件。

我的目标是通过此路线访问Home及其所有参数:

<PrivateRouteComponent path="/home" component={Home} />

这是我的课堂内容:

class PrivateRouteComponent extends Component{
    constructor(props) {
        super(props);
    }

    render() {
        let renderView = (this.props) => ( // <-- Shows an error for this
        FakeServer.isUserAuthenticated() == true // Dummy mockup server
            ? <Component {...this.props} />
            : <Redirect to='/login' />
        )
        return (
            <Route {...rest} render={renderView} />
        )
    }

}

我在renderView定义行看到错误,说:

 Parsing error: Invalid left-hand side in arrow function parameters

2 个答案:

答案 0 :(得分:0)

扩展@AnshulBansal在评论中所说的内容,您将renderView声明为函数,但是将this.props用作函数参数,这是错误的。

let renderView = (this.props) => ( 
                  ^^^^^^^^^^

您正在将函数的参数定义为类的属性的值(这是我对此的最佳解释,我知道那不是最好的方法)

看看renderView的作用,看来您确实不需要该函数的任何参数:

let renderView = () => ( 
  FakeServer.isUserAuthenticated() == true 
    ? <Component {...this.props} />
    : <Redirect to='/login' />
  )

如果需要该函数具有参数,则应执行以下操作:

let renderView = (props) => {
  // do something
}
// ...
renderView(this.props)

或者,您也可以使用默认参数

let renderView = (props = this.props) => {
  // do something
}

答案 1 :(得分:0)

好的,我通过添加mapStateToProps,mapDispatchToProps函数并简化了渲染来解决了这个问题。

class PrivateRouteComponent extends Component{

constructor(props) {
    super(props);

}

componentDidMount() {
    let userObj = FakeServer.getAuthenticatedUser()
    this.props.getUserByUsername(userObj.user.username) // Mapped by connect()
}

render() {
    return (
        this.props.loading ? 'Loading in router' :
        <Route {...this.props} render={(props) => (
            FakeServer.isUserAuthenticated() == true
                ? <Component {...props} />
                : <Redirect to='/login' />
        )} />
    )
}

}

/*
mapStateToProps
Function to relate reducer results with props:
 */
const mapStateToProps = state => ({
    user: state.userReducer.user,
    loading: state.userReducer.loading
});

/*
mapDispatchToProps
Function to map dispatcher trigger functions as pros:
 */
function mapDispatchToProps(dispatch){
    return {
        getUserByUsername : (username) => {dispatch(userActions.getUserByUsername(username))}
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(PrivateRouteComponent);