Redirecting a user to a different path in React

问题: I'm building a web app. The user can go and Read some info about an object from Firebase. The problem is the user can also be logged in with an Android app, and if a proper...

问题:

I'm building a web app. The user can go and Read some info about an object from Firebase. The problem is the user can also be logged in with an Android app, and if a property on Firebase is changed, he needs to be kicked out of his current view on the web app. I know how to get this one done. This is the code:

var AssignedWordRef = firebase.database().ref('Users').child(currentUser.uid).child('assignedWork');
AssignedWordRef.on('value', snapshot => {
    var assignmentId = snapshot.val();
    if (assignmentId === null) {
        console.log('Redirect right here mate');
    }
});

And this works. It's console logging and all is great. But the problem is I need to redirect the user to a different path. So far I used a window.location, but it's a bad idea. Here are my Routes:

<Switch>
    <Route exact path="/assignments" render={
        () => (firebase.auth().currentUser === null ?
            <Redirect to='/'/> : this.state.assignedWord === undefined ?
                <AssignmentsComponent/> :
                <Redirect to={'/assignment/' + this.state.assignedWord}/>)
    }/>

    <Route exact path='/assignment/:id' render={
        props => (
            firebase.auth().currentUser === null ?
                <Redirect to='/'/> : <CheckIfHasCurrentTasksComponent {...props}/>)
    }/>

    <Route exact path='/userPanel' render={
        () => (firebase.auth().currentUser === null ?
            <Redirect to='/'/> : <UserPannelComponent/>)
    }/>

    <Route exact path="/" component={HomeComponent}/>
</Switch>

I tried returning the <ComponentToRedirectTo/> where the console.log is, but no luck.

Returning <Redirect to='/assignments'/> also didn't help. My guess is I have to put it in the Route, but I have no idea how.


回答1:

Use push with this.props.history or just use the Redirect. This is an example code from another answer (remember to use this.setState) to perform a new rendering:

class MyComponent extends React.Component {
  state = {
    redirect: false
  }

  handleSubmit () {
    axios.post(/**/)
      .then(() => this.setState({ redirect: true }));
  }

  render () {
    const { redirect } = this.state;

     if (redirect) {
       return <Redirect to='/somewhere'/>;
     }

     return <RenderYourForm/>;
}

回答2:

You can try this.props.history.push('/'); instead of using <Redirect to='/' />

Hope this will work!

  • 发表于 2018-07-05 15:31
  • 阅读 ( 314 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除