首页 > 解决方案 > React Not Found 渲染服务器端

问题描述

我使用React Router v4,效果很好。

<Switch>
    <Router path="/users/:uid" component={Profile} />
    <Router path="*" component={NotFound} />
</Switch>

好的,如果我访问域/blabla NotFound组件渲染得很好。


但我想知道当用户不存在时如何渲染NotFound 。/users/:uid

app.get('/users/:uid', (req, res) {
    if( // user exist) { 
        res.json({user})
    } 

    else res.status(404).json({ message: 'User not exist'})
})

也许我需要连接服务器响应,但我不知道什么是最好的方法。

class Profile extends Component {

   componentWillMount = () => {
       this.props.fetchUser(uid)
   }

   render(){

       if(!this.props.loading && !this.props.user) return <NotFound />
       else return (...)
   }
}

这是正确的方法吗?我一起使用redux。

标签: reactjsreduxreact-routerreact-router-v4

解决方案


class Profile extends Component {
   render(){
       if(!this.props.loading && !this.props.user) {
        this.props.history.push('/bababa') // you can jump to notFound
        return
      }
       else return (...)
   }
 }

这是?


推荐阅读