【问题标题】:Error: Invalid hook call. Hooks can only be called inside of the body of a function component. When using useEffect错误:无效的挂钩调用。钩子只能在函数组件的主体内部调用。使用 useEffect 时
【发布时间】:2020-11-11 19:50:36
【问题描述】:

我在这段代码中遇到了 Invalid Hook 错误:

import React, { useState, useEffect } from 'react'
import { useLocation, useHistory, Link } from 'react-router-dom'
import $ from 'jquery'

import '../stylesheet/pages/pages.landing.css'
import '../stylesheet/global.css'

export default function Landing() {

    function useQuery() {
        return new URLSearchParams(useLocation().search);
    }

    useEffect(() => {
        alert('a')
    }, [])
}

错误在useEffect行,你们能帮帮我吗?

在我的 Routes 脚本中调用了 Landing:

import { BrowserRouter, Route, Switch } from 'react-router-dom';

import Landing from './pages/Landing';

export default function routes() {
    return (
        <BrowserRouter>
            <Switch>
                <Route path="/" exact children={Landing} />
            </Switch>
        </BrowserRouter>
    )
}

【问题讨论】:

  • Landing 在哪里被调用,你能把代码贴出来吗?
  • 在我的 routes.js 文件中...更新问题

标签: reactjs react-hooks


【解决方案1】:

children 属性被称为 作为普通函数 when you need to render,而不是作为组件 - 钩子可能只存在于通过 JSX 语法创建的元素中,这些元素被转换为 React.createElement

虽然您可以在内联 children 属性中使用 JSX 语法调用 Landing

children={() => <Landing />}

使用component 属性会更合适:

<Route path="/" exact component={Landing} />

【讨论】:

    猜你喜欢
    • 2021-10-02
    • 2019-11-21
    • 2021-10-31
    • 1970-01-01
    • 2022-11-27
    • 2021-11-11
    • 2021-10-23
    • 2020-11-20
    • 2021-12-26
    相关资源
    最近更新 更多