gpt4 book ai didi

javascript - React - useMemo 有一个复杂的表达式 - 将其提取到一个单独的变量中,以便对其进行静态检查

转载 作者:行者123 更新时间:2023-12-04 14:15:17 25 4
gpt4 key购买 nike

我正在尝试使用 useMemo但是我从 lint 收到了一条消息:

React Hook useMemo has a complex expression in the dependency array. Extract it to a separate variable so it can be statically checked react-hooks/exhaustive-deps.



会是什么呢?
const [selectedDate, setSelectedDate] = useState("Escolha uma data para pagamento");
const itens = useMemo(() => {
if (!contrato.propostas || contrato.propostas.length == 0) return [];
let dates = contrato.propostas.map(p => p.vencimento)
dates = Array.from(new Set(dates)).map((item) => ({
id: item,
option: item
}))
if (dates.length === 1 && selectedDate !== contrato.filterByDate) setSelectedDate(dates[0].option)
if (contrato.filterByDate && dates.find(d => d.id === contrato.filterByDate) !== -1) setSelectedDate(contrato.filterByDate);
return dates;
}, [JSON.stringify(contrato.propostas), contrato.filterByDate, selectedDate])
contratocontrato.propostas是对象。 contrato.filterByDate是一个字符串。
我试图找到一个悬而未决的问题,但我找不到。

最佳答案

它告诉你这样做:

const [selectedDate, setSelectedDate] = useState("Escolha uma data para pagamento");
const temp = JSON.stringify(contrato.propostas);
const itens = useMemo(() => {
// ...
}, [temp, contrato.filterByDate, selectedDate])

但我不明白你为什么要字符串化 contrato.propostas .您从不使用字符串化版本,因此它实际上不是依赖项。只要您保持数据不可变(正如您应该使用react),那么您只需将 contrato.propostas 直接放入依赖数组中:
const [selectedDate, setSelectedDate] = useState("Escolha uma data para pagamento");
const itens = useMemo(() => {
// ...
}, [contrato.propostas, contrato.filterByDate, selectedDate])

关于javascript - React - useMemo 有一个复杂的表达式 - 将其提取到一个单独的变量中,以便对其进行静态检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60836743/

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