使用历史记录重定向后是否可以保持状态

时间:2019-05-15 16:12:15

标签: reactjs

您好,我的问题是,在我使用history.push()重定向到组件之后,我在那儿传递了一些用户详细信息,并通过它传递了这个问题,即当您单击刷新或重定向到另一个组件时,所有内容都丢失了,甚至是未定义的内容。我在这里找到了解决方案,但前提是您在同一台服务器上。由于我使用的是Java jersey API,因此无法使用https://stackoverflow.com/a/36623117/11416547那里提供的解决方案,因此将变量设置为state也不起作用。感谢您的任何提前帮助。

onSubmit = e => {
        e.preventDefault();
        fetch(  `/myresource/customer/auth/${this.state.query}/${this.state.password}`,
            {
                method: "POST",
                headers: {
                    credentials: "same-origin"

                },
                credentials: "include",
            })
            .then(res => res.json())
            .then((result) => {
                    this.setState({
                       user: result.customer,

                    });
                    console.log(result.customer);

                    this.cookies.set('token', result.newCookie, { path: '/' });

                    console.log(this.cookies.get('token'));

                    const { history } = this.props;
                    if(history) history.push({
                        pathname: '/dashboard/',                   <-- here i redirect to this component and pass user there
                        search: '',
                        state: {user: result.customer}
                    });
                }
            )
    }


this is my dashboard Component
 constructor(props) {
    super(props);

    this.state = {
        userName: '',
    }

}

componentDidMount() {
    if (typeof(this.props.location.state) != "undefined" ) {  
        this.setState( {userName: this.props.location.state.user.userName},
            () => {userName: this.props.location.state.user.userName}
        );
    }
}

render() {
    return (
      <Container>
          <div>{this.state.userName}</div>
      </Container>
    );
}

I am asking how to keep the state alive on the client side after i redirect to a component with history.push i am not trying to achieve the ``` history.push```  functionality for which is asked in the possible duplicated question how to redirect.

0 个答案:

没有答案