将数据从实用程序文件发送到组件(React + Vite)

huangapple go评论62阅读模式
英文:

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 块中设置错误状态,并将其与 usersignout 值一起传递给 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 = () =&gt; {
  const context = useContext(UserContext);
  if (context === undefined) {
    throw new Error(&quot;useUserContext was used outside of its Provider&quot;);
  }
  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 }) =&gt; {
  const [user, setUser] = useState(null);
  const [error, setError] = useState(null);

  const signout = () =&gt; setUser(null);

  useEffect(() =&gt; {
    const fetchUser = () =&gt; {
      fetch(&quot;https://localhost:8000/api/&quot;)
        .then((response) =&gt; response.json())
        .then((result) =&gt; setUser(result.results))
        .catch((error) =&gt; setError(error)); // set error state here
    };
    fetchUser();
  }, []);

  const contextValue = useMemo(
    () =&gt; ({ user, signout, error }), // pass error value here
    [user, signout, error]
  );

  return (
    &lt;UserContext.Provider value={contextValue}&gt;{children}&lt;/UserContext.Provider&gt;
  );
};

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 = () =&gt; {
  const { user, signout, error } = useUserContext(); // use custom hook here

  return (
    &lt;div className=&quot;login-page&quot;&gt;
      {user ? (
        &lt;div&gt;
          &lt;h1&gt;Welcome, {user.name.first}&lt;/h1&gt;
          &lt;button onClick={signout}&gt;Sign out&lt;/button&gt;
        &lt;/div&gt;
      ) : (
        &lt;div&gt;
          &lt;h1&gt;Please log in&lt;/h1&gt;
          {error &amp;&amp; &lt;p className=&quot;error-message&quot;&gt;{error.message}&lt;/p&gt;} // display
          error message here
        &lt;/div&gt;
      )}
    &lt;/div&gt;
  );
};

To learn more, see

huangapple
  • 本文由 发表于 2023年7月7日 07:38:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76633110.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定