在这篇文章React Hooks -理解组件重新呈现中,我了解到当我们在父组件中使用useContext
Hook时,只有使用上下文的子组件将重新呈现。
文章给出了语境的两种消费方式。看一下代码片段:
有效使用useContext
import React from "react";
import ReactDOM from "react-dom";
import TickerComponent from "./tickerComponent";
import ThemedTickerComponent from "./themedTickerComponent";
import { ThemeContextProvider } from "./themeContextProvider";
import ThemeSelector from "./themeSelector";
import "./index.scss";
import logger from "./logger";
function App() {
logger.info("App", `Rendered`);
return (
<ThemeContextProvider>
<ThemeSelector />
<ThemedTickerComponent id={1} />
<TickerComponent id={2} />
</ThemeContextProvider>
);
}
import React, { useState } from "react";
const defaultContext = {
theme: "dark",
setTheme: () => {}
};
export const ThemeContext = React.createContext(defaultContext);
export const ThemeContextProvider = props => {
const setTheme = theme => {
setState({ ...state, theme: theme });
};
const initState = {
...defaultContext,
setTheme: setTheme
};
const [state, setState] = useState(initState);
return (
<ThemeContext.Provider value={state}>
{props.children}
</ThemeContext.Provider>
);
};
import React from "react";
import { useContext } from "react";
import { ThemeContext } from "./themeContextProvider";
function ThemeSelector() {
const { theme, setTheme } = useContext(ThemeContext);
const onThemeChanged = theme => {
logger.info("ThemeSelector", `Theme selection changed (${theme})`);
setTheme(theme);
};
return (
<div style={{ padding: "10px 5px 5px 5px" }}>
<label>
<input
type="radio"
value="dark"
checked={theme === "dark"}
onChange={() => onThemeChanged("dark")}
/>
Dark
</label>
<label>
<input
type="radio"
value="light"
checked={theme === "light"}
onChange={() => onThemeChanged("light")}
/>
Light
</label>
</div>
);
}
module.exports = ThemeSelector;
import React from "react";
import { ThemeContext } from "./themeContextProvider";
import TickerComponent from "./tickerComponent";
import { useContext } from "react";
function ThemedTickerComponent(props) {
const { theme } = useContext(ThemeContext);
return <TickerComponent id={props.id} theme={theme} />;
}
module.exports = ThemedTickerComponent;
import React from "react";
import { useState } from "react";
import stockPriceService from "./stockPriceService";
import "./tickerComponent.scss";
function TickerComponent(props) {
const [ticker, setTicker] = useState("AAPL");
const currentPrice = stockPriceService.fetchPricesForTicker(ticker);
const componentRef = React.createRef();
setTimeout(() => {
componentRef.current.classList.add("render");
setTimeout(() => {
componentRef.current.classList.remove("render");
}, 1000);
}, 50);
const onChange = event => {
setTicker(event.target.value);
};
return (
<>
<div className="theme-label">
{props.theme ? "(supports theme)" : "(only dark mode)"}
</div>
<div className={`ticker ${props.theme || ""}`} ref={componentRef}>
<select id="lang" onChange={onChange} value={ticker}>
<option value="">Select</option>
<option value="NFLX">NFLX</option>
<option value="FB">FB</option>
<option value="MSFT">MSFT</option>
<option value="AAPL">AAPL</option>
</select>
<div>
<div className="ticker-name">{ticker}</div>
<div className="ticker-price">{currentPrice}</div>
</div>
</div>
</>
);
}
module.exports = TickerComponent;
useContext的低效使用
import React from "react";
import ReactDOM from "react-dom";
import { useContext } from "react";
import TickerComponent from "./tickerComponent";
import ThemedTickerComponent from "./themedTickerComponent";
import { ThemeContextProvider } from "./themeContextProvider";
import { ThemeContext } from "./themeContextProvider";
function App() {
const { theme, setTheme } = useContext(ThemeContext);
const onThemeChanged = theme => {
setTheme(theme);
};
return (
<>
<div style={{ padding: "10px 5px 5px 5px" }}>
<label>
<input
type="radio"
value="dark"
checked={theme === "dark"}
onChange={() => onThemeChanged("dark")}
/>
Dark
</label>
<label>
<input
type="radio"
value="light"
checked={theme === "light"}
onChange={() => onThemeChanged("light")}
/>
Light
</label>
</div>
<ThemedTickerComponent id={1} />
<TickerComponent id={2} theme="" />
</>
);
}
在中低效地使用useContext例如,子组件TickerComponent (2)
自父组件以来没有使用重新渲染的上下文<App />
消耗上下文并重新渲染。但是在中,useContext的有效使用例如,子TickerComponent(2)没有重新渲染,即使它的父元素<ThemeContxtProvider>
因为消费背景下重新呈现。
我知道没有React的孩子。当父元素重新呈现时,memo会重新呈现,所以为什么在中使用useContext没有发生的例子?
你的问题是你正在考虑像
这样的代码function ComponentToRender() {
const count = React.useRef(0)
React.useEffect(() => {
console.log('component rendered', count.current++)
})
return null
}
function App() {
const [count, setCount] = useState(0);
return (
<div>
<h2>You clicked {count} times!</h2>
<button onClick={() => setCount(count + 1)}>Increment</button>
<ComponentToRender />
</div>
);
}
和
function ComponentToRender() {
const count = React.useRef(0)
React.useEffect(() => {
console.log('component rendered', count.current++)
})
return null
}
function Clicker({ children }) {
const [count, setCount] = useState(0);
return (
<div>
<h2>You clicked {count} times!</h2>
<button onClick={() => setCount(count + 1)}>Increment</button>
{children}
</div>
);
}
function App() {
return (
<Clicker>
<ComponentToRender />
</Clicker>
);
}
等价的。虽然它们做同样的事情,行为或多或少以相同的方式,第二个例子将只渲染ComponentToRender
一次,即使在按下"increment"按钮多次。(而第一个将重新渲染每次按下按钮。)
这个概念也适用于你的例子。你的"低效消费"将触发App
的重新渲染,并强制刷新该组件的每个直接子组件。"高效消费"不会,因为事实并非如此。在我的简化示例中,ComponentToRender
实际上是由App
呈现的,而不是Clicker
。因此,Clicker
状态的变化不会影响ComponentToRender
(它只是作为子节点传递)
App
的另一种写法是:
function App() {
const componentToRenderWithinApp = <ComponentToRender />
return (
<Clicker>
{componentToRenderWithinApp}
</Clicker>
);
}
这个等价于<Clicker><ComponentToRender /></Clicker>