在 React 上将 props 从一个组件传递到另一个组件

Pass props from a Component to another Component on React

我已从 react-google-login 登录。我需要将电子邮件从一个名为 Login 的组件传递到另一个名为 User 的组件(用户应该在其中看到他的电子邮件)。

class Login extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      email: "",
      redirecting: false,
    };
  }
  render() {
    const responseGoogleSuccess = (response) => {
      this.setState({ email: response.profileObj.email });
      this.setState({ redirecting: true });
    };
    return (
      <div>
        <GoogleLogin
          clientId="myclientid"
          buttonText="Log in"
          onSuccess={responseGoogleSuccess}
          cookiePolicy={"single_host_origin"}
        />
        {this.state.redirecting ? <Redirect to="/user" /> : null}
      </div>
    );
  }
}

您必须将 email 状态移动到 LoginUser 组件的 common 父级或使用您可以阅读的上下文 api在 Doc 中,实现您的想法的最困难途径是使用 redux,它是一种状态管理

你有很多方法可以解决这个问题。

1.<Redirect to={/user/${this.state.email}} />

您可以使用 this.props.match.params.email

在用户组件中访问此电子邮件

2.you 可以将电子邮件存储在 redux store 中,并在用户组件中访问。

3.you 可以使用上下文 api.