【发布时间】:2019-06-09 11:18:05
【问题描述】:
我们可以通过一个空数组作为钩子中的第二个参数来防止对 useEffect 进行不必要的计算:
// that will be calculated every single re-rendering
useEffect(() => {...some procedures...})
// that will be calculated only after the first render
useEffect(() => {...some procedures...}, [])
但是,对于我们不能像上面那样做的 useContext 钩子,提供第二个参数。 还有,我们不能用useCallback、useMemo来包装useContext。 例如,我们有一个组件:
const someComponent = () => {
const contextValue = useContext(SomeContext);
const [inputValue, setInputValue] = useState('');
return (
<Fragment>
<input value={inputValue} onChange={onInputChange} />
<span>{contextValue}</span>
</Fragment>
)
问题是每次输入都会重新渲染,我们每次都会有不必要的 useContext 重新渲染。其中一个决定是在两个上制动组件:
const WithContextDataComponent = () => {
const contextValue = useContext(SomeContext);
return <JustInputComponent contextValue={contextValue} />
const JustInputComponent = (props) => {
const [inputValue, setInputValue] = useState('');
return <input value={inputValue} onChange={onInputChange} />
所以,现在问题消失了,但是我们有两个组件。而在上面的组件中,我们应该导入<WithContextDataComponent />,而不是<SomeComponent />,我认为这有点难看。
我可以在不拆分为两个组件的情况下停止对 useContext 不必要的重新渲染吗?
【问题讨论】:
-
嗯。你的组件被重新渲染不是因为
useContext,而是因为useState的处理程序(onInputChange)被调用。或者即使没有输入字段,您是否看到组件重新渲染?
标签: reactjs react-hooks