react自定义钩子更改输入值并在其他组件上显示



我有三个react文件

useUser.js

import React, { useState } from "react";
const useUser = () => {
const [username, setUsername] = useState();
const [showProfile, setShowProfile] = useState();
return { username, setUsername, showProfile, setShowProfile };
};
export default useUser;

第二个文件是Login.js

import React from "react";
import { useState } from "react";
import useUser from "../customHooks/useUser";
const Login = () => {
const { setUsername, setShowProfile } = useUser();
return (
<div>
<div>
<input
type="text"
className="m-2 p-2"
placeholder="Enter your email here"
onChange={(e) => {
setUsername(e.target.value);
}}
/>
</div>
<div>
<input
type="text"
className="m-2 p-2"
placeholder="Enter your password here"
onChange={(e) => {}}
/>
</div>
<div>
<button
className="m-2 p-2"
onClick={() => {
setShowProfile(true);
}}>
Login
</button>
</div>
</div>
);
};
export default Login;

然后是Profile.js

import React from "react";
const Profile = () => {
return (
<div>
<h1 className="text-3xl">Profile</h1>
<h2 className="text-2xl font-semibold">username: </h2>
</div>
);
};
export default Profile;

然后联系

import React, { useEffect, useState } from "react";
import Login from "../components/Login";
import Profile from "../components/Profile";
import useUser from "../customHooks/useUser";
const contact = () => {
const { username, showProfile } = useUser();
return (
<div>
<Login></Login>
{showProfile && <Profile />}
<div>username is : {username}</div>
</div>
);
};
export default contact;

我想在登录中更新用户名输入的值,并使用自定义userUser钩子来设置用户名和setShowprofile,并使用该值来显示或隐藏配置文件。是可能的还是我需要使用useContext钩子。我试图避免使用useContext钩子。谢谢。

有几个选项。最简单的解决方案是让您的Contact组件(LoginProfile的父组件)成为useUser钩子的消费者,并将其传递给LoginProfile

const Contact = () => {
const { username, setUsername, showProfile, setShowProfile } = useUser();
return (
<div>
<Login setShowProfile={setShowProfile} setUsername={setUsername} />
{showProfile && <Profile username={username} />}
</div>
);
}

第二个选项是使用useContext钩子。这有点复杂,我建议不要在这种情况下使用它,除非您的用例变得更复杂。这里有一篇很好的博客文章,关于它可能看起来像什么

使用useUser钩子的每个实例都会导致由不同组件管理的一组不同的状态。

你要么需要在react树中所有组件的共同锚点上创建这个状态,并通过props向下传递相关的函数和值,要么对整个应用程序使用某种状态管理。

react文档的相关部分似乎是这样的。

我建议从合理的小型应用程序的通用锚定方法开始,当它变得乏味时,看看其他替代方法(想到redux)。