React Not Found渲染服务器端

时间:2018-10-17 06:07:01

标签: reactjs redux react-router react-router-v4

我使用 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。

1 个答案:

答案 0 :(得分:0)

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 (...)
   }
 }

是吗?

相关问题