英文:
Sending data from utility file to a component (React + Vite)
问题
我有一个名为LoginPage.jsx
的文件,它调用了一个名为AuthContext.jsx
的实用程序文件中的函数,该实用程序文件处理向后端服务器发出的用户身份验证请求。如果未找到用户或返回任何其他错误,我如何将其发送回LoginPage.jsx
文件以进行处理并显示给用户?
英文:
I've got a file called LoginPage.jsx
which calls a function in a utility file called AuthContext.jsx
, the utility file handles the request to the backend server to authenticate a user. If no user is found or any other error is returned, how do I send that back to the LoginPage.jsx
file to be handled and displayed to the user?
答案1
得分: 1
将错误从上下文传递到组件的一种可能方法是使用一个自定义钩子,该钩子包装了 useContext
函数,并在上下文未定义时抛出错误。这样,您可以在使用该钩子的任何组件中访问上下文值,并相应地处理错误。例如,您可以创建一个名为 useUserContext
的钩子,如下所示:
const useUserContext = () => {
const context = useContext(UserContext);
if (context === undefined) {
throw new Error("useUserContext was used outside of its Provider");
}
return context;
};
然后,在您的 AuthContext.jsx
文件中,您可以在 fetch
请求的 catch 块中设置错误状态,并将其与 user
和 signout
值一起传递给 UserContext.Provider
:
const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
const signout = () => setUser(null);
useEffect(() => {
const fetchUser = () => {
fetch("https://localhost:8000/api/")
.then((response) => response.json())
.then((result) => setUser(result.results))
.catch((error) => setError(error)); // 在此处设置错误状态
};
fetchUser();
}, []);
const contextValue = useMemo(
() => ({ user, signout, error }), // 在此处传递错误值
[user, signout, error]
);
return (
<UserContext.Provider value={contextValue}>{children}</UserContext.Provider>
);
};
最后,在您的 LoginPage.jsx
文件中,您可以使用 useUserContext
钩子来访问错误值,并在存在时向用户显示它:
const LoginPage = () => {
const { user, signout, error } = useUserContext(); // 在此处使用自定义钩子
return (
<div className="login-page">
{user ? (
<div>
<h1>Welcome, {user.name.first}</h1>
<button onClick={signout}>Sign out</button>
</div>
) : (
<div>
<h1>Please log in</h1>
{error && <p className="error-message">{error.message}</p>} // 在此处显示错误消息
</div>
)}
</div>
);
};
要了解更多信息,请参阅以下链接:
英文:
One possible way to pass error from context to component is to use a custom hook that wraps the useContext
function and throws an error if the context is undefined. This way, you can access the context value in any component that uses the hook, and handle the error accordingly. For example, you can create a useUserContext
hook like this:
const useUserContext = () => {
const context = useContext(UserContext);
if (context === undefined) {
throw new Error("useUserContext was used outside of its Provider");
}
return context;
};
Then, in your AuthContext.jsx
file, you can set the error state in the catch block of your fetch
request, and pass it along with the user
and signout
values to the UserContext.Provider
:
const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
const signout = () => setUser(null);
useEffect(() => {
const fetchUser = () => {
fetch("https://localhost:8000/api/")
.then((response) => response.json())
.then((result) => setUser(result.results))
.catch((error) => setError(error)); // set error state here
};
fetchUser();
}, []);
const contextValue = useMemo(
() => ({ user, signout, error }), // pass error value here
[user, signout, error]
);
return (
<UserContext.Provider value={contextValue}>{children}</UserContext.Provider>
);
};
Finally, in your LoginPage.jsx
file, you can use the useUserContext hook to access the error value and display it to the user if it exists:
const LoginPage = () => {
const { user, signout, error } = useUserContext(); // use custom hook here
return (
<div className="login-page">
{user ? (
<div>
<h1>Welcome, {user.name.first}</h1>
<button onClick={signout}>Sign out</button>
</div>
) : (
<div>
<h1>Please log in</h1>
{error && <p className="error-message">{error.message}</p>} // display
error message here
</div>
)}
</div>
);
};
To learn more, see
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论