Javascript 条件未命中-有条件地呈现React组件
我不知道为什么不管isAuthenticated是否为假,它总是以渲染而不是点击。当isAuthenticated为false时,您可能会认为它显然会命中重定向,但事实并非如此Javascript 条件未命中-有条件地呈现React组件,javascript,reactjs,Javascript,Reactjs,我不知道为什么不管isAuthenticated是否为假,它总是以渲染而不是点击。当isAuthenticated为false时,您可能会认为它显然会命中重定向,但事实并非如此 class ProtectedRoute extends Component { render() { console.log(`ProtectedRoute: isAuthenticated: ${this.props.isAuthenticated}`) const ComponentToRend
class ProtectedRoute extends Component {
render() {
console.log(`ProtectedRoute: isAuthenticated: ${this.props.isAuthenticated}`)
const ComponentToRender = this.props.component,
RouteToRender = (
<Route
{...this.props}
render={() =>
(this.props.isAuthenticated ? (<ComponentToRender {...this.props} />) :
(<Redirect
to={{
pathname: '/login',
state: {from: this.props.location
}}}
/>))}
/>)
return (RouteToRender)
}
}
类ProtectedRoute扩展组件{
render(){
console.log(`ProtectedRoute:isAuthenticated:${this.props.isAuthenticated}`)
const componentorender=this.props.component,
RouteToRender=(
(this.props.isAuthenticated?():
())}
/>)
返回(RouteToRender)
}
}
以下是我调试WebStorm时在RouteToRender中看到的内容:
我所做的只是强制重定向,我注意到我还必须删除{…this.props}和状态:{from:this.props.location},这样做有效:
class ProtectedRoute extends Component {
render() {
console.log(`ProtectedRoute: isAuthenticated: ${this.props.isAuthenticated}`)
const ComponentToRender = this.props.component,
RouteToRender = (
<Route
render={() =>
(<Redirect
to={{
pathname: '/login'
}}
/>)}
/>)
return (RouteToRender)
}
类ProtectedRoute扩展组件{
render(){
console.log(`ProtectedRoute:isAuthenticated:${this.props.isAuthenticated}`)
const componentorender=this.props.component,
RouteToRender=(
()}
/>)
返回(RouteToRender)
}
所以这可能是我继承道具的一个问题。下面是使用此组件的调用的样子:
<ProtectedRoute component={DashboardContainer} path='/dashboard' />
所以我也收到了这些道具。。。(组件和路径)
修复程序:
<Route
render={({this.props}) =>
(this.props.isAuthenticated ? (<ComponentToRender {...this.props} />) :
(<Redirect
to={{
pathname: '/login',
state: {from: this.props.location
}}}
/>))}
/>)
(this.props.isAuthenticated?():
())}
/>)
实际上,它并没有完全修复它,但至少它没有渲染组件,如果!我被认证了。但是现在,我的上一次更改导致了另一个问题,如果isAuthenticated为true,则它不会渲染,可能是因为自从我从中删除{…this.props}后,它不再具有路径您正在将组件和渲染作为道具发送到路由组件。由于组件属性可用,路由将渲染该组件,而不是触发渲染。我在这里尝试模拟PrivateRoute函数: