小编Max*_*Max的帖子

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

我想在常规函数中使用我的自定义钩子,如下所示,但 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 …
Run Code Online (Sandbox Code Playgroud)

reactjs react-hooks

6
推荐指数
1
解决办法
8672
查看次数

标签 统计

react-hooks ×1

reactjs ×1