gpt4 book ai didi

javascript - 为什么这段代码同时使用 useMemo 和 createSelector?

转载 作者:行者123 更新时间:2023-12-04 11:30:45 26 4
gpt4 key购买 nike

The React-Redux documentation provides this example for when a selector is used in multiple component instances and depends on the component's props.

import React, { useMemo } from 'react'
import { useSelector } from 'react-redux'
import { createSelector } from 'reselect'

const makeNumOfTodosWithIsDoneSelector = () =>
createSelector(
state => state.todos,
(_, isDone) => isDone,
(todos, isDone) => todos.filter(todo => todo.isDone === isDone).length
)

export const TodoCounterForIsDoneValue = ({ isDone }) => {
const selectNumOfTodosWithIsDone = useMemo(
makeNumOfTodosWithIsDoneSelector,
[]
)

const numOfTodosWithIsDoneValue = useSelector(state =>
selectNumOfTodosWithIsDone(state, isDone)
)

return <div>{numOfTodosWithIsDoneValue}</div>
}

export const App = () => {
return (
<>
<span>Number of done todos:</span>
<TodoCounterForIsDoneValue isDone={true} />
<span>Number of unfinished todos:</span>
<TodoCounterForIsDoneValue isDone={false} />
</>
)
}

在函数 TodoCounterForIsDoneValue ,作者为什么要换行 makeNumOfTodosWithIsDoneSelectoruseMemo ?我对 createSelector 的理解来自 reselect是它生成了一个内存选择器,那么“双重”内存这个选择器的目的是什么?

最佳答案

因为每个组件都需要自己唯一的选择器实例来正确内存行为。如果许多组件使用相同的选择器实例,并且每个组件都传入自己不同的参数(例如 selectThingById(state, props.itemId) ),则选择器永远不会正确内存。通过为每个组件创建一个唯一的实例,每个选择器可以传入自己单独的参数并获得一致的内存。

关于javascript - 为什么这段代码同时使用 useMemo 和 createSelector?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62450825/

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