gpt4 book ai didi

javascript - React.memo - 永远不会调用第二个参数 "areEqual"

转载 作者:行者123 更新时间:2023-12-05 07:03:50 24 4
gpt4 key购买 nike

我的父组件处理对服务器的请求并为其子组件提供来自响应的数据。在这种情况下,一个子组件(FilterSidebar:包含过滤器组件)应该只呈现一次,因为过滤器将从初始请求的数据创建。

这就是为什么我要使用 React 的 memo hook。相应的数据只传递一次到过滤器组件。 areEqual 函数中的日志永远不会被调用,组件将始终再次呈现。

父组件:

import React, { useState, useRef } from "react";
import { useQuery } from '@apollo/react-hooks';
import { REQUEST_INQUIRIES } from './requests/REQUEST_INQURIES.js'
import Canvas from './components/Canvas.js';
import FilterSidebar from './components/filter/FilterSidebar.js';
import Loader from './components/Loader.js'
import QueryContext from './components/filter/query-context.js'

const App = () => {

const [query, setQuery] = useState(["{\"name\": {\"$LIKE\": \"%\"}}"])

// used to create filters once with initial data
const [keys, setKeys] = useState([])
const [values, setValues] = useState([])
const ref = useRef(false);

const { loading, data, error } = useQuery(REQUEST_INQUIRIES, {
variables: { filters: `{ \"$AND\": [ ${query.map(q => { return q})} ]}` }
})

const addQuery = (queryPart) => {
if (!query.includes(queryPart)) setQuery(prevState => [...prevState, queryPart])
}

const contextValue = { query, addQuery }

// return loading animation here
if (loading) { return <Loader /> }

// return some kind of error message here
if (error) { return <p>Error...</p> }

const { edges } = data.getHMCInquiryListing

if (!ref.current) {
// will only be called once

// some data transformation ...

setKeys(tmpKeys)
setValues(tmpValues)
ref.current = true;
}

return (
<QueryContext.Provider value={contextValue}>
<FilterSidebar keys={keys} values={values} />
<Canvas data={edges} />
</QueryContext.Provider>
)


}

export default App;

子组件:

import React, { memo } from "react"
import GenericFilter from './GenericFilter.js'
import SpecificFilter from './SpecificFilter.js'

const FilterSidebar = (props) => {

const {keys, values} = props

return (
<div className='filter-sidebar'>
<div className="filters">
<GenericFilter attributes={keys} />
{keys.map(attribute => {
return <SpecificFilter key={attribute} attribute={attribute} values={values[attribute]} />
})}
</div>
</div>
);

}

const areEqual = (prevProps, nextProps) => {
console.log(prevProps, nextProps)
}

export default memo(FilterSidebar, areEqual)

提前致谢。

最佳答案

memo 仅在重新渲染时有效,因为您传递的是状态变量 key,它不会重新渲染而是创建组件的新引用,并且它永远不会将 prev props 与新 props 进行比较,因为它认为它是一个全新的组件。您可以在其文档中了解 React 如何使用键作为决定何时重新呈现组件的因素之一。

关于javascript - React.memo - 永远不会调用第二个参数 "areEqual",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63101812/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com