Redux库easy有一个名为computed的函数,它可以替代标准的Redux选择器:
import { computed } from 'easy-peasy'
const model = {
session: {
totalPrice: computed(state => state.price + state.tax)
}
}然后在组件中调用选择器,如下所示:
import { useStoreState } from 'easy-peasy'
function TotalPriceOfProducts() {
const totalPrice = useStoreState(state => state.products.totalPrice)
return <div>Total: {totalPrice}</div>
}问题是,似乎没有办法将输入传递给选择器。如果需要处于状态的数组中的特定对象,则不能将对象的ID作为输入传递。我唯一的选择是在组件端这样做。Redux选择器具有函数的优点,因此我可以传递要在选择器逻辑中使用的输入。
有人用过这个问题吗?
发布于 2022-09-30 11:44:49
我不能将对象的ID作为输入传递
要启用这个功能,您必须返回一个函数作为计算属性。。
下面是一个示例,公开一个计算函数getTodoById
import { computed } from 'easy-peasy'
const model = {
todos: [],
getTodoById: computed(state => {
// Note how we are returning a function instead of state
//
return (id) => state.todos.find(t => t.id === id)
})
}然后你可以像这样使用它:
import { useStoreState } from 'easy-peasy'
function Todo({ id }) {
const getTodoById = useStoreState(state => state.getTodoById)
const matchingTodo = getTodoById(id);
// ... etc
}https://stackoverflow.com/questions/71579925
复制相似问题