更好的方法来破坏具有多个回报的Custom React Hooks?

问题描述 投票:2回答:2

Context:

我看到文档o反应钩子和所有钩子返回两个在数组中被破坏的值。但是,如果我有一个钩子返回一个多于两个的数组,如下所示:

const [value, someMethod, someMethod2, someMethod3, someMethod4] = useSomeMethod(someValue)

但我只想要一些方法,而不是全部。在这种情况下,我需要做类似的事情:

const [value, , , someMethod3, someMethod4] = useSomeMethod(someValue)

这样,它看起来并不那么糟糕,但想象一下如果你有一个返回超过10的钩子。我将展示一个真实的例子,这样可以更清楚。

Real example:

我正在创建一个用于处理数组的钩子,所以它会是这样的:

const useArray = (initialState) => {

    const [array, setArray] = useState(initialState)

    const add = (value) => {
        let newArray = [...array, value]
        setArray(newArray)
    }

    const deleteByIndex = (index) => {
        let newArray = array.filter((x, i) => i != index)
        setArray(newArray)
    }

    const updateByIndex = (value, index) => {
        let newArray = [...array]
        newArray[index] = value
        setArray(newArray)
    }

    return [array, add, deleteByIndex, updateByIndex]
}

并使用这个钩子,它会像:

const [bananas, addBananas, deleteBananasByIndex, updateBananasByIndex] = useArray(someBananas)

但是如果你知道一点点数组操作,那么有超过3种方法,可能超过10种。

我想要做的是为数组创建一个钩子,它可以处理数组的所有类型的操作,并在我的项目中的任何地方使用它。

The Problem:

当我要使用这个钩子时会出现问题,因为当我调用钩子时所有方法都不会被使用,但是所有方法都将在项目中使用。并且只使用一些方法,它将是这样的:

const [value, oneMethod, , , someMethod, , otherMethod, , moreMethod] = useSomeMethod(someValue)

我认为这是非常糟糕的,因为我需要记住其他方法,并且使用大量的,看起来不太好。

我想把它解构为一个对象,但是名字会被修复,而且我也无法在一个组件中使用更多的那个useArray

因此,考虑到所有这些......

是否有更好的方法来破坏具有多个回报的自定义反应钩,而不是记住回报的顺序并使用大量的qazxsw poi?

观察:我的问题不是关于数组,而是关于破坏反应钩的返回

javascript reactjs react-hooks
2个回答
0
投票

您可以对函数的返回值使用过滤器,并仅采用所需的值并进行结构化(如果您无法更改数据结构)

,

如果你可以改变你的结构,只需使用const [value, oneMethod, someMethod, otherMethod, moreMethod] = useSomeMethod(someValue).filter((_,index)=> select desired index only) 而不是destructure

object

0
投票

Update

正如const { foo: bar } = { foo: 7 , xyz: some value} 在评论中所说,worc是一个更好的方法,也是正确的方法,像这样的情况是使用useReducer

此外,这是如何工作:

useReducer

感谢所有帮助过的人!


所以这样做的方法是返回一个对象并重命名所有变量

function arrayReducer(array, action) {
    switch (action.type) {
        case 'push':
            return [...array, action.value]
        case 'deleteByIndex':
            let deleteByIndex = array.filter((x, i) => i != action.index)
            return deleteByIndex
        case 'updateByIndex':
            let updateByIndex = [...array]
            updateByIndex[action.index] = action.value
            return updateByIndex
        default:
            throw new Error()
    }
}

export default function useArray(initialState){
    return useReducer(arrayReducer, initialState)
}
© www.soinside.com 2019 - 2024. All rights reserved.