Hook改變的React Component寫法思路(3) - useContext

首先我們回憶一下React Context API的用法(生產者消費者模式)。
創建context對象:

// context初始值
const INITIAL_VALUE = ‘’;
const MyContext = React.createContext(INITIAL_VALUE);

劃定context使用的範圍,管理它的值:

function App() {
    return (
        <MyContext.Provider value=“context value”>
            <ConsumeComponent />
        </MyContext.Provider>
    );
}

獲取context的值:

function ConsumeComponent() {
    return (
        <MyContext.Consumer>
            {contextValue => (
                <div>
                    <MyComponent value={contextValue} />
                    <div>{contextValue}</div>
                </div>
            )}
        </MyContext.Consumer>
    );
}

可以看到,使用Hook之前,消費這個context API是使用render props的方式。那如果這個context是一個原始數據,並不是用來直接顯示的時候,就需要繁瑣的特殊處理(比如傳入到下一層component處理),讓人不免尷尬。
有了useContext hook之後,這就不再是個問題了。我們只需要修改消費者那一步:

function ConsumeComponent() {
    const contextValue = useContext(MyContext);
    return (
        <div>
            <MyComponent value={contextValue} />
            <div>{contextValue}</div>
        </div>
    );
}

context的值可以直接賦值給變量,然後想處理或者渲染都可以。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章