React中的受保护路线,未传递参数

时间:2018-11-18 00:26:15

标签: reactjs react-router

我正在尝试创建一条受保护的路由,如下面的代码所示:

const PrivateRoute = ({component:Component, authenticated, ...rest}) =>{
    console.log(authenticated);
   return(
        <Route {...rest} render={(props) => (
            authenticated === true
            ? <Component {...props} {...rest} />
            : <Redirect to="/Login"/>
        )} />);

    }
export default PrivateRoute;

我在路由器配置中传递了以下参数:

<PrivateRoute component={Appointments} authenticated={this.state.authenticated} exact path="/appointments" render={(props) => <Appointments {...props} appointments={this.state.appointments} />} />

但是,当我尝试路由时,似乎没有将“ appointments = {this.state.appointments}”道具传递给“ Appointments”组件。

这是我得到的错误

TypeError:无法读取未定义的属性“地图”

知道可能是什么问题吗?

2 个答案:

答案 0 :(得分:0)

我认为这里的问题是,您正在PrivateRoute的render属性中传递道具,就像render={(props) => <Appointments {...props} appointments={this.state.appointments} />}一样。现在,PrivateRoute中的实际组件呈现中未使用此属性。在路线初始化期间尝试执行以下操作:

<PrivateRoute component={Appointments} authenticated={this.state.authenticated} exact path="/appointments"  appointments={this.state.appointments} />

这应该可以解决您的问题。我在这里建议,您可以使用React HOC在实际组件上创建身份验证包装,而不是创建自己的PrivateRoute。

答案 1 :(得分:0)

function PrivateRoute({children,... rest}){

 const isAuthenticated = (location) => {
    //if loading show loading indicator
 }

const childrenWithLocation = (location) => Children.map(children, child => {
    if (isValidElement(child)) {
        return cloneElement(child, { to: child.props?.to + location.search });
    }
    return child;
});

return (
    <Route
        {...rest}
        render={({ location }) =>
            isAuthenticated(location)
                ? (childrenWithLocation(location))
                : (<Redirect
                    to={{
                        pathname: "/login" + location.search,
                        state: { from: location }
                    }}
                />)
        }
    />
);

}