什么是context
Context 提供了一個無需為每層組件手動添加 props,就能在組件樹間進(jìn)行數(shù)據(jù)傳遞的方法。
在 React 中,數(shù)據(jù)是通過 props 屬性自上而下進(jìn)行傳遞的。但是當(dāng)某些屬性是許多組件都需要的(例如:地區(qū)偏好,UI 主題),這樣就需要通過組件樹的逐層傳遞 props,極其繁瑣。Context 提供了一種在組件之間共享此類值的方式,使得不必再顯式地逐層傳遞props。
何時使用 Context
當(dāng)需要共享那些對于一個組件樹而言是“全局”的數(shù)據(jù),例如當(dāng)前認(rèn)證的用戶、主題或首選語言。
何時避免使用Context
Context 主要應(yīng)用于很多不同層級的組件需要訪問一些同樣的數(shù)據(jù)。因為這會使得組件的復(fù)用性變差,所以要謹(jǐn)慎使用。
如果你只是想避免層層傳遞一些屬性,組件組合有時候是一個比 context 更好的解決方案。
React.createContext
const MyContext = React.createContext(defaultValue);
創(chuàng)建一個 Context 對象。當(dāng) React 渲染一個訂閱了這個 Context 對象的組件,這個組件會從組件樹中離自身最近的那個匹配的 Provider 中讀取到當(dāng)前的 context 值。只有當(dāng)組件所處的樹中沒有匹配到 Provider 時,其 defaultValue 參數(shù)才會生效。
Context.Provider
<MyContext.Provider value={/* 某個值 */}>
每個 Context 對象都會返回一個 Provider React 組件,它允許consumer組件訂閱 context 的變化。
- 一個 Provider 可以和多個消費組件有對應(yīng)關(guān)系。多個 Provider 也可以嵌套使用,里層的會覆蓋外層的數(shù)據(jù)。
- 當(dāng) Provider 的 value 值發(fā)生變化時,它內(nèi)部的所有消費組件都會重新渲染。Provider 及其內(nèi)部 consumer 組件都不受制于 shouldComponentUpdate 函數(shù),因此當(dāng) consumer 組件在其祖先組件退出更新的情況下也能更新。
Class.contextType
掛載在 class 上的 contextType 屬性會被重賦值為一個由 React.createContext()創(chuàng)建的 Context 對象。這能讓你使用 this.context 來消費最近 Context 上的那個值。你可以在任何生命周期中訪問到它,包括 render 函數(shù)中。
class MyClass extends React.Component {
componentDidMount() {
let value = this.context;
/* 在組件掛載完成后,使用 MyContext 組件的值來執(zhí)行一些有副作用的操作 */
}
componentDidUpdate() {
let value = this.context;
/* ... */
}
componentWillUnmount() {
let value = this.context;
/* ... */
}
render() {
let value = this.context;
/* 基于 MyContext 組件的值進(jìn)行渲染 */
}
}
MyClass.contextType = MyContext;
或者使用 public class fields 語法,用 static 屬性來初始化 contextType。
class MyClass extends React.Component {
static contextType = MyContext;
render() {
let value = this.context;
/* 基于這個值進(jìn)行渲染工作 */
}
}
Context.Consumer
<MyContext.Consumer>
{value => /* 基于 context 值進(jìn)行渲染*/}
</MyContext.Consumer>
需要將函數(shù)作為子元素,這個函數(shù)接收當(dāng)前的 context 值,返回一個 React 節(jié)點。傳遞給函數(shù)的 value 值等同于往上組件樹離這個 context 最近的 Provider 提供的 value 值。如果沒有對應(yīng)的 Provider,value 參數(shù)等同于傳遞給 createContext() 的 defaultValue。
Context.displayName
context 對象接受一個名為 displayName 的屬性,類型為字符串。React 開發(fā)者工具使用該字符串來確定 context 要顯示的內(nèi)容。
const MyContext = React.createContext(/* some value */);
MyContext.displayName = 'MyDisplayName';
<MyContext.Provider> // "MyDisplayName.Provider" 在 開發(fā)工具 中
<MyContext.Consumer> // "MyDisplayName.Consumer" 在 開發(fā)工具 中
動態(tài) Context
Provider的value值,使用父組件中的state,state變化,context的value也隨之變化。
在嵌套組件中更新 Context
從一個在組件樹中嵌套很深的組件中更新 context 是很有必要的。在這種場景下,可以通過 context 傳遞一個函數(shù),使得 consumers 組件可以更新 context。
// 確保傳遞給 createContext 的默認(rèn)值數(shù)據(jù)結(jié)構(gòu)是調(diào)用的組件(consumers)所能匹配的!
export const ThemeContext = React.createContext({
theme: themes.dark,
toggleTheme: () => {},
});
消費多個 Context
為了確保 context 快速進(jìn)行重渲染,React 需要使每一個 consumers 組件的 context 在組件樹中成為一個單獨的節(jié)點。
// Theme context,默認(rèn)的 theme 是 “l(fā)ight” 值
const ThemeContext = React.createContext('light');
// 用戶登錄 context
const UserContext = React.createContext({
name: 'Guest',
});
class App extends React.Component {
render() {
const {signedInUser, theme} = this.props;
// 提供初始 context 值的 App 組件
return (
<ThemeContext.Provider value={theme}>
<UserContext.Provider value={signedInUser}>
<Layout />
</UserContext.Provider>
</ThemeContext.Provider>
);
}
}
function Layout() {
return (
<div>
<Sidebar />
<Content />
</div>
);
}
// 一個組件可能會消費多個 context
function Content() {
return (
<ThemeContext.Consumer>
{theme => (
<UserContext.Consumer>
{user => (
<ProfilePage user={user} theme={theme} />
)}
</UserContext.Consumer>
)}
</ThemeContext.Consumer>
);
}
注意事項
如果context的value為一個對象,當(dāng)每一次 Provider 重渲染時,會重渲染所有下面的 consumers 組件。原因是 value 屬性總是被賦值為新的對象。
// 觸發(fā)意外的渲染
class App extends React.Component {
render() {
return (
<MyContext.Provider value={{something: 'something'}}>
<Toolbar />
</MyContext.Provider>
);
}
}
將 value 狀態(tài)提升到父節(jié)點的 state 中,防止這種情況的出現(xiàn)
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
value: {something: 'something'},
};
}
render() {
return (
<Provider value={this.state.value}>
<Toolbar />
</Provider>
);
}
}