React-useContext ExampleDev, React

Context Example

JSX Example

构建 Provider

import React, { createContext } from "react";
import ReactDOM from "react-dom";

/* Step1: 新建一个 Context */
const MessageContext = createContext();

myApp = () => {
  return (
    {/* Step2: Context.Provider 包裹子组件, 并且传递 Props */}
    <MessageContext.Provider value="hello">
      <div>
        <Test />
      </div>
    </MessageContext.Provider>
  );
};

构建 Consumer

方法 1:

Test = () => {
  return (
    <MessageContext.Consumer>
      {(value) => <div> message : {value} </div>}
    </MessageContext.Consumer>
  );
};

一般大家会用 useContext 的另一种方法:

import { useContext } from "react";
Test = () => {
  const messageValue = useContext(MessageContext);
  return <div>Message: {messageValue} </div>;
};

TSX Example

Provider

/* Step1: Create Context */
const AuthContext = React.createContext<
  | {
      user?: User;
      register: (form: AuthForm) => Promise<void>;
      login: (form: AuthForm) => Promise<void>;
      logout: () => Promise<void>;
    }
  | undefined
>(undefined);

AuthContext.displayName = "AuthContext";


/* Step2: Wrap children with Provider */
export const AuthProvider = ({ children }: { children: ReactNode }) => {
  const [user, setUser] = useState<User | undefined>();
  const [isLoading, setIsLoading] = useState(true);

  const login = /* ... */
  const register = /* ... */
  const logout = /* ... */

  return (
    <AuthContext.Provider
      children={children}
      value={{ user, register, login, logout }}
    />
  );
};

/* Step2.5: useContext helper to make code elegant */
export const useAuth = () => {
  const context = useContext(AuthContext);
  if (!context) {
    throw new Error("useAuth must be used within an AuthProvider");
  }
  return context;
};

Consumer

Its Pretty Easy

const Login = () => {
  const { login, user } = useAuth();
  console.log("user: ", user);
  /* ... */

};
Powered by Remix
|
Designed by szhshp
|
Copyright © szhshp 2022