如何在React组件之间传递身份验证

时间:2019-10-25 02:10:27

标签: reactjs

我无法在React组件之间传递身份验证。

当用户单击“登录”按钮时,我想要的显示为true。我怎样才能做到这一点?我想保留App组件中的Logout组件,以便在每个页面中显示。

在此处共享我的代码:https://repl.it/@GustavoMonti/loginlogout

2 个答案:

答案 0 :(得分:1)

要执行的4个步骤,每个步骤都有大量的堆栈溢出主题。

a)在App.js上设置状态钩子

b)然后通过一种更改状态的方法

c)通过路由器传递方法-另一个核心主题Pass a function through React Router

讨论得很好的话题

d)调用方法

未实现注销,您可以执行相同的方法,并将app.js中的状态更改为false,以通过方法

const App = () => {
//set the state
  const [isLogged, setIsLogged] = useState(false);
  const changeLogStatus = () => {
    setIsLogged(true);
  };
  return (
    <div>
      <div className="App">
        Hi you are Logged? {isLogged ? "true" : "false"}
        <Routes changeStatus={changeLogStatus} />
      </div>
      <div>

        <Logout isLogged={isLogged} />
      </div>
    </div>
  );
};

export default App;

export default function Routes(props) {
  return (
    <Router history={history}>
      <Switch>
// see how the method is passed through the router , very important!
        <Route
          path="/"
          exact
          render={propss => (
            <Login history={history} changeFn={props.changeStatus} />
          )}
        />
        <Route path="/dashboard" exact component={Dashboard} />
        <Route path="/logout" exact component={Logout} />
      </Switch>
    </Router>
  );
}


// then call the method to change the state in the app.js
const Login = props => {
  const [auth, setAuth] = useState(null);

  async function handleSubmit(event) {
    event.preventDefault();
    setAuth(true);
    props.changeFn();   // calling the method
    props.history.push("/dashboard");
  }

  return (
    <>
      <h1>Login</h1>
      <form onSubmit={handleSubmit}>
        <button className="btn" type="submit">
          Enter
        </button>
      </form>
    </>
  );
};

export default Login;

答案 1 :(得分:1)

如果您想在整个会话中存储值以进行响应,则可以采用几种方法。

  1. 使用react-global-configuration

npm install react-global-configuration

然后在您的登录组件中:

import config from 'react-global-configuration';
config.set({auth: 'true'})

然后将其用作其他任何组件

config.get('auth')
  1. 使用LocalStorage

    localStorage.setItem('auth','true') localStorage.getItem('auth')

  2. 使用React-Router历史记录

登录

this.props.history.push({
            pathname: '/Home',
            state: {
              auth: 'true'
            }
          });

和“家庭”组件中的

var myAuth = this.props.location.state.auth