如何修改父组件中的状态,并将其作为道具传递给子组件,但只有当修改后的状态发生变化时才重新渲染这些子组件?
我的基本设置目前是可行的,但会造成一些不必要的重渲染。父组件从URL中获取信息(使用react-router钩子)并修改它,然后将其作为道具传递给它的子组件。该组件看起来像这样。
const myComponent = () => {
const { dataType } = useParams();
const { search } = useLocation();
/// These functions help me transform that data into something more manageable
const y = queryString.parse(search).collection;
const { collections, gqlQuery } = getCollections(dataType);
const collection = collections.find(x => x.value === y);
return (
<MyChild collection={collection} /> ... This component is re-rendering unnecessarily.
)
};
我怎样才能确保当URL没有变化时(URL) dataType
和 search
的值),接收派生数据的子组件也不会不必要地重新渲染?
第一步是要确保引用到 collection
变量只有在其中一个依赖关系改变时才会改变。
useMemo(() => {
const y = queryString.parse(search).collection;
const { collections, gqlQuery } = getCollections(dataType);
const collection = collections.find(x => x.value === y);
}, [search, dataType]);
第二个参数是确保组件只有在收到新道具时才会重新渲染。
import { memo } from 'react';
function Child() {
}
export default memo(Child);
你也可以使用第二个参数 memo
以自定义比较的内容。
function Child(props) {
}
function areEqual(prevProps, nextProps) {
/*
return true if passing nextProps to render would return
the same result as passing prevProps to render,
otherwise return false
*/
}
export default React.memo(Child, areEqual);
React.memo - DocsReact.useMemo - Docs
PS:请注意,React的重渲染速度通常超快。在衡量其影响后,只将这些作为性能提升使用。有可能它有 今非昔比