使用React Hooks新特性useReducer、useContext替代傳統Redux高階組件案例


當我們使用redux進行數據管理的時候,一般都是在根組件通過Provider的方式引入store,然后在每個子組件中,通過connect的方式使用高階組件進行連接,這樣造成的一個問題是,大量的高階組件代碼冗余度特別高,既然hooks帶來了新特性,不如一起來用用看

目錄結構如下:

  • action/example/index.js:
    我們還使用redux的思想,編寫action
  • reducer/example/index.js:
    處理action,不同於redux的reducer,這里我們可以不用提供初始狀態
  • 根組件App.js:
    Provider提供給子組件context
    useReducer定義的位置,引入一個reducer並且提供初始狀態initialState
  • 子組件component/example/example.js:
    useContext定義的位置,獲取祖先組件提供的context
    useEffect用於進行異步請求

1.reducer/example/index.js

import * as Types from '../../types/types';

export const defaultState = {
    count: 0
}

export default (state, action) => {
    switch(action.type) {
        case Types.EXAMPLE_TEST:
            return {
                ...state,
                count: action.count
            }
        default: {
            return state
        }
    }
}

2.action/example/index.js

import * as Types from '../../types/types';

export const onChangeCount = count => ({
    type: Types.EXAMPLE_TEST,
    count: count + 1
})

3.根組件App.js

import React, { useReducer } from 'react';
import Example from './test/example';
import example, { defaultState } from './reducer/example';

export const ExampleContext = React.createContext(null);

const App = () => {

	const [exampleState, exampleDispatch] = useReducer(example, defaultState);

	return (
		<ExampleContext.Provider value={{exampleState, dispatch: exampleDispatch}}>
			<Example />
		</ExampleContext.Provider>
	);
}

export default App;

4.子組件component/example/example.js

import React, { useState, useEffect, useReducer, useContext } from 'react';

import actions from '../../action';
import { ExampleContext } from '../../App';

const Example = () => {

    const exampleContext = useContext(ExampleContext);

    useEffect(() => {
        window.document.title = `you click ${exampleContext.exampleState.count} times`;
    }, [exampleContext.exampleState.count]);

    return (
        <div>
            <p>you can click it</p>
            <button onClick={() => exampleContext.dispatch(actions.onChangeCount(exampleContext.exampleState.count))}>click it</button>
        </div>
    )
}

export default Example;

5.types/types.js

export const EXAMPLE_TEST = 'EXAMPLE_TEST';

總結

使用useContext()時候我們不需要使用Consumer了。但不要忘記export和import上下文對象


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM