如何在刷新后不丢失道具的情况下通过道具传递路线?

时间:2019-12-21 21:11:32

标签: reactjs react-router

一旦用户通过身份验证,我会将从Login.js的TextField中提取的userId从Login.js传递到Company.js到Dashboard.js。

Login.js

class Login extends Component {

  state = {
    //state
  }

  loginHandler = (event) => {
     //authentication check
    this.props.history.push({
              pathname: '/company/dashboard',
              state:{
                  userId: this.state.username,
              }
         });
  }

  render() {
    return (
      //html code
    )
  }
}

export default withRouter(Login);

Company.js

class Company extends Component {

    constructor(props){
        super();
        console.log(props.history.location.state.userId)
        this.state = {
            userId: props.history.location.state.userId
        }
    }

    drawerList = {
        'Profile':['profile', <DashboardIcon />],
    }

    render() {
        return (
            <div>
                <Dashboard userId={this.state.userId} drawerList={this.drawerList}>
                     <Route exact path="/company/dashboard/profile" component={Profile} />
                </Dashboard>
            </div>
        );
    }
}
export default withRouter(Company);

Dashboard.js

function ClippedDrawer(props) {
    const buttonHandler = (text) => {
        props.history.push(props.match.path + '/' + props.drawerList[text][0]);
    }

    return (
        <div className={classes.root}>
            <CssBaseline />
            <AppBar position="fixed" className={classes.appBar}>
                <Toolbar>
                    <Typography variant="h6" noWrap>
                        PICT PLACEMENT - {props.history.location.state.userId}
                    </Typography>
    );
}

export default withRouter(ClippedDrawer);

一切正常。我使用userId登录并将其带到公司仪表板,但是如果刷新公司仪表板页面:
TypeError:props.history.location.state未定义(在Company.js中)

是因为一旦刷新状态丢失了吗?我应该如何传递userId以便在刷新后仍保留它,或者我需要使用会话?

3 个答案:

答案 0 :(得分:1)

状态从根本上不存储在刷新中,刷新仅保留URL本身。您有两种选择:

将用户ID存储在URL中

此选项的优点是用户可以更改自己的用户ID

将路线更改为

<route path="/company/dashboard/:user_id">

Company中,使用props.params.user_id代替props.state.user_id

并替换为:

this.props.history.push({
          pathname: '/company/dashboard',
          state:{
              userId: this.state.username,
          }
     });

与此:

this.props.history.push({
          pathname: '/company/dashboard/'+userId,
     });

将用户存储在Cookies或本地存储中

而不是对props.state.user_idlocalStorage.getItem(user_id)。使用localStorage.setItem来正确更新登录组件中的用户ID。

此方法的优点是用户看不到他的ID,并且如果他登录和注销ID都将保持不变。

答案 1 :(得分:0)

将用户信息存储在本地存储中。您可以通过npm安装它。因此刷新后将不会被清洗。因此,如果基本的if语句是否本地存储包含用户信息,则将其作为道具传递。

答案 2 :(得分:0)

根据文档 https://reactrouter.com/web/api/history,props.history.location.state 是可变的,因此您应该使用道具位置。

他们是这样解释的:

<块引用>

它也可以在 history.location 上找到,但你不应该使用它 因为它是可变的。您可以在历史文档中阅读更多相关信息。 位置对象永远不会改变,因此您可以在生命周期中使用它 钩子来确定导航何时发生,这对于 数据获取和动画