React组件props控制台打印undefined但DevTools可见,portalId找不到
嘿,我一眼就瞅出你这个问题的症结所在了——你的PrivateRoute组件没把自定义的portalId props传递给最终渲染的Home组件,这就导致控制台里拿不到,但React DevTools能看到(因为DevTools能追踪到传给PrivateRoute的所有props)。
问题到底出在哪?
看你定义的PrivateRoute代码:
PrivateRoute = ({ component: Component, ...rest }) => ( <Route {...rest} render={props => ( this.state.isAuthenticated ? <Component {...props} /> : <Redirect to="/" /> )}/> )
你把portalId这类自定义props放到了...rest里,然后传给了<Route {...rest} />,但Route组件只会处理它自己认识的属性(比如path、exact),剩下的自定义props并不会自动跑到render函数的props里。你现在只把路由相关的props(比如match、location、history)传给了Home,但漏掉了rest里的portalId!
怎么修复?
很简单,把rest里的自定义props和路由的props一起传给Component就行,修改后的PrivateRoute代码如下:
PrivateRoute = ({ component: Component, ...rest }) => ( <Route {...rest} render={routeProps => ( this.state.isAuthenticated ? <Component {...routeProps} {...rest} /> : <Redirect to="/" /> )}/> )
我把render的参数改成routeProps是为了和外层的rest区分开,避免混淆。现在Home组件就能同时拿到路由相关的props和你传递的portalId了。
额外小提醒
你提到portalId是fetch请求后才设置的,要确保在portalId有值之前,组件不会因为拿到undefined报错——不过既然DevTools能看到这个props,说明值已经正确设置了,所以主要问题就是上面的props传递遗漏。
另外,如果你的PrivateRoute是独立的函数组件,记得不要用this.state,改用useState或者上下文来获取认证状态,但看你的写法是在类组件内部定义的,所以暂时用this.state.isAuthenticated没问题。
内容的提问来源于stack exchange,提问作者Vincent Nguyen

