首页 > 解决方案 > React 使用 Hooks 处理链接的条件渲染

问题描述

我正在尝试根据用户登录做一些基本的条件渲染。我在登录组件中有我的事件处理程序和 axios 调用。

const Login = () => {

  const handleChange = event => {
    setCustomerLogin({
      ...customerLogin,
      [event.target.name]: event.target.value
    });
  };

  const handleSubmit = e => {
    e.preventDefault();

    axios
      .post("/api/Authentication", customerLogin)
      .then(function(response) {
        setCustomerLogin(response.data);
        console.log(response);
      })
      .catch(function(error) {
        console.log(error);
      });

  };

我的导航栏组件现在非常基本,只是自动呈现我的 SignedOutLinks,这是我在用户登录之前显示的链接。

const Navbar = () => {
    return (
        <nav className="nav-wrapper blue darken-4">
            <div className="container">
                <Link to='/' className="brand-logo left">Cars4U</Link>
                <SignedOutLinks />
            </div>
        </nav>
    )
};

我想在 App.js 中定义我的 setCustomerLogin 函数并让我的登录组件调用这个值。到目前为止,这是我的 App.js 文件,我只是不确定如何在我的 App.js 中定义函数并在我的登录组件中设置状态

const [customerLogin, setCustomerLogin] = useState([
    { username: "", password: "" }
  ]);

function App() {
    return(
        <div className="App">
            <Navbar />
            <Switch>
                <Route path='/login' component={Login}/>                    
                <Route path='/signup' component={Signup}/>
            </Switch>
        </div>
    );
}

标签: reactjsreact-hooks

解决方案


你可以将 state setter( setCustomerLogin) 和 state value( )作为 propscustomerLogin传递给你的组件:Login

const [customerLogin, setCustomerLogin] = useState([
    { username: "", password: "" }
  ]);

function App() {
    return(
        <div className="App">
            <Navbar />
            <Switch>
                <Route path='/signup' component={Signup}/>
                <Route
                  path="/login"
                  render={() => 
                   <Login 
                    customerLogin={customerLogin} 
                    setCustomerLogin={setCustomerLogin}
                   />}
                 />
            </Switch>
        </div>
    );
}

请注意,我使用了一些不同的语法来路由Login组件,你仍然会得到相同的结果,只是现在你可以将任何你想要的 props 传递给组件来呈现。您可以在此处阅读有关这种路由的更多信息。

然后,您可以Login通过 props 在组件中访问它们:

const Login = ({setCustomerLogin, customerLogin}) => {

  const handleChange = event => {
    setCustomerLogin({
      ...customerLogin,
      [event.target.name]: event.target.value
    });
  };

  const handleSubmit = e => {
    e.preventDefault();

    axios
      .post("/api/Authentication", customerLogin)
      .then(function(response) {
        setCustomerLogin(response.data);
        console.log(response);
      })
      .catch(function(error) {
        console.log(error);
      });

  };

推荐阅读