React:在常规函数中使用自定义钩子

Max*_*Max 6 reactjs react-hooks

我想在常规函数中使用我的自定义钩子,如下所示,但 React 不允许我这样做。我想知道我的 useUrl 自定义挂钩是否无效,或者调用挂钩时出现问题。

const handleAddFormation = async () => {
    console.log('add formation')

    await useUrl('POST', 'http://localhost:1337/formations', newFormationList)

    setNewFormationList([])
    setModalOpen(false)
}
Run Code Online (Sandbox Code Playgroud)

我的自定义钩子:

export default function useUrl(method, url, args) {
    const [data, setData] = useState([])
    const [loading, setLoading] = useState(true)

    useEffect(() => {
        setLoading(true)
        axios({
            method,
            url,
            data: args
        })
        .then((res) => {
            setData(res.data)
            setLoading(false)
        })
        .catch((err) => {
            console.log(err)
            setLoading(false)
        })
    }, [])

    if (!loading) return data
}
Run Code Online (Sandbox Code Playgroud)

这给了我以下错误:

React Hook "useUrl" is called in function "handleAddFormation" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter
Run Code Online (Sandbox Code Playgroud)

Oro*_*Oro 4

来自反应文档

\n

不要\xe2\x80\x99t 从常规 JavaScript 函数调用 Hook。相反,您可以:

\n

\xe2\x9c\x85 从 React 函数组件调用 Hooks。

\n

\xe2\x9c\x85 从自定义 Hook 调用 Hook

\n

另外,您不需要使用await自定义挂钩

\n