React Hook - useContext

我在Study React所撰寫的第一個範例是系統的登入與登出,而登入狀態需要由上層元件傳遞給登入與登出元件做修改。在這範例中,由於上層元件與登入元件只有一層,所以我可以透過建構元將狀態傳遞過去;然而登出元件與上層元件相差太多層,傳遞並不是那麼容易。

在React Hook推出之前,有flux、Redux,或者是後來推出的Context,都可以解決這個問題;而本篇要介紹的useContext,我認為比前面幾個都還容易達到需求。

以一個登入畫面為例,我們在App元件中,希望能透過authState來決定該顯示登入畫面又或者是登入後的畫面;假如使用者尚未登入,那我們會將會Route至登入畫面,即LoginForm元件。在LoginForm中,如果使用者成功登入後,會去修改這個authState;而React會因為這個狀態的改變,重新render App元件並Route至登入後的畫面。我將在App中createContext,而LoginForm將會useContext去做狀態的修改。

首先透過React.createContext建立共用的Context變數AuthContext。在App元件中,透過useState宣告了成員變數authState,並使用AuthContext.Provider將變數分享給下層元件。從程式碼可以得知,如果authState為true就會render DefaultLayout元件;反之則是LoginForm元件。

export const AuthContext = React.createContext(null);
 
function App(){
  const [ authState, setAuthState ] = useState(false);
 
  let route_target;
  if( !authState) {
    route_target = <Route path="/" name="Login" component={LoginForm}/>;
  } else
    route_target = <Route path="/" name="Home" component={DefaultLayout} />;
 
  return (
    <AuthContext.Provider value={[authState, setAuthState]}>
      <HashRouter>
        <Switch>
        {route_target}
        </Switch>
      </HashRouter>
    </AuthContext.Provider>
  );
}

在我的LoginForm元件中,可以透過useContext去拿到authState與setAuthState。當使用者輸入帳號密碼並點擊Login Button後,會觸發handleSubmit,接著它會透過Auth.signIn去執行登入動作。在這裡會根據登入成功與否,去透過setAuthState更新authState。

function LoginForm(){
  const [ authState, setAuthState ] = useContext(AuthContext);
  const [ username, setUserName ] = useState("");
  const [ password, setPassword ] = useState("");
  const [ feedback, setFeedBack ] = useState(null);
 
  const validateForm = ()=>{
    return username.length > 0 && password.length > 0;
  }
 
  const handleSubmit = (e)=>{
    e.preventDefault();
    try {
      Auth.signIn(username, password);
      setAuthState(true);
    } catch( err ) {
      setFeedBack(err.message);
    }
  }
 
  const showFeedback = ()=>{
    return feedback != null;
  }
 
  return (
 
    <div className="Login">
      <form onSubmit={handleSubmit}>
        <FormGroup>
          <Label>Username</Label>
          <Input
            autoFocus
            aria-label="username-input"
            type="text"
            value={username}
            onChange={e=>setUserName(e.target.value)}
          ></Input>
        </FormGroup>
        <FormGroup>
          <Label>Password</Label>
          <Input
            value={password}
            aria-label="password-input"
            onChange={e=>setPassword(e.target.value)}
            type="password"
          ></Input>
        </FormGroup>
        <Button
          block
          disabled={!validateForm()}
          type="submit"
          onClick={()=>{}}
        >
          Login
        </Button>
        <br/>
        <Alert color="danger" isOpen={showFeedback()} fade={true} aria-label="feedback">{feedback}</Alert>
      </form>
 
    </div>
  );
}

在單元測試部分,為了要傳遞共享的Context資料給LoginForm,於是我做了一個中繼的LoginFormComp,使用方式類似App的做法。除此之外,我使用了React Hook的useEffect;當LoginForm修改了登入狀態,它就會觸發useEffect裡面的動作,在這我用來標記登入成功與否。可以直接參考測試“Login success”,在輸入帳號密碼與點擊Login Button後,就可以驗證authState是否為true。假如要模擬登入失敗的情況,可以使用mockImplementation讓它拋出例外。

import {render, fireEvent, cleanup} from 'react-testing-library';
import React, { useState, useEffect } from 'react';
import LoginForm from '../LoginForm/LoginForm';
import { AuthContext } from "../../../App";
import Auth from "../Components/Auth/Auth"
 
let authState = false;
function LoginFormComp(){
    const [ state, setState ] = useState(false);
    useEffect(()=>{
        authState = state;
    });
    return <AuthContext.Provider value={[state, setState]}><LoginForm/></AuthContext.Provider>;
}
 
 
describe('<LoginForm/>',()=>{
    afterEach(cleanup);
 
    const inputLoginInfo = (utils, username, password)=>{
        const username_input = utils.getByLabelText('username-input');
        const password_input = utils.getByLabelText('password-input');
 
        fireEvent.change(username_input, {
            target: { value: username }
        });
        fireEvent.change(password_input, {
            target: { value: password }
        });
    };
 
    const clickLoginBtn = (utils)=>{
        const loginButton = utils.getByText('Login');
        fireEvent.click(loginButton);
    };
 
    const givenAuthSignInSuccessfully = ()=>{
        const auth_do_nothing = jest.fn();
        auth_do_nothing.mockImplementation(()=>{});
        Auth.signIn = auth_do_nothing.bind(Auth);
    };
 
    it('Login success', ()=>{
        // given
        givenAuthSignInSuccessfully();
        const formComp = render(<LoginFormComp/>);
 
         // when
         inputLoginInfo(formComp, 'ADMIN', 'ADMIN');
         clickLoginBtn(formComp);
 
        // then
        expect(authState).toBeTruthy();
    });
});

本篇文章中,我的Context僅儲存一個boolean變數;假如你的資料較為複雜,是可以透過json去建置資料。除此之外,針對資料部分,也可以獨立做成Model元件。後續有機會會再分享關於較複雜資料與jest的使用細節。