使用React Router v4时出现‘Objects are not valid as a React child’错误排查
React Router v4中Auth认证组件的"Objects are not valid as a React child"错误排查
我来帮你拆解下这个问题的根源,以及怎么修复它。
你的代码重现
首先先整理下你提供的代码片段:
Auth.js的render方法
render() { const { Component: component, ...rest } = this.props; return ( <Route> {rest} render={props => this.isAuth === true ? ( <Component {...props} /> ) : ( <Redirect to={{ pathname: "/login" }} /> ) } </Route> ); }
Index.js的路由声明片段
render( <BrowserRouter> <div className="App"> <Switch> <Route path="/login" component={Login} /> {/* 这里应该是你用Auth组件包裹的受保护路由 */} {/* <Auth path="/dashboard" component={Dashboard} /> */} </Switch> </div> </BrowserRouter> );
错误原因分析
这个报错的核心问题非常明确:你把{rest}直接放在了<Route>标签的内部作为子元素渲染,但rest是一个对象(里面包含了路由相关的props,比如path、exact这类属性),React完全不允许直接渲染对象类型的子元素,这就触发了"Objects are not valid as a React child"的错误。
正确的做法是把rest里的属性作为Route组件的props属性传递,而不是当成子元素。
修正后的Auth组件代码
render() { const { Component: Component, ...rest } = this.props; return ( // 关键修改:把{...rest}作为Route的属性展开传递,而非放在标签内部 <Route {...rest} render={props => this.isAuth === true ? ( <Component {...props} /> ) : ( <Redirect to={{ pathname: "/login" }} /> )} /> ); }
补充说明
当你用<Auth path="/dashboard" exact component={Dashboard} />这种方式使用组件时,rest会包含path、exact这些路由规则属性,通过{...rest}把它们传递给Route组件,才能让Route正确识别路由匹配规则,同时彻底避免对象作为子元素渲染的错误。
内容的提问来源于stack exchange,提问作者Jamie Aden
相关产品推荐
相关产品推荐

