错误:无效的挂钩调用。钩子只能在函数组件的主体内部调用。 - 反应

时间:2021-05-14 16:25:23

标签: javascript reactjs

所以我试图声明一个状态,然后进行 API 调用,然后设置状态,但我遇到了 Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 错误。我已经检查了我的 react 版本和 react dom,它很好,而且我没有 React 的两个副本。这是我的代码的简化版本:

function RandomScreen(){
    const [State, setState] = useState([])
    
    let history = useHistory()
    var style = require('./Random.css')
    
    useEffect(async function(){
        // Make API call
        .then(function(response){
            setState(response.data)
        })
    }, [])
    
    async function handleClick(){
        // Make API call
        // Set State again
    }
    return (
        // Some HTML code
    )
}

App.js

function App(){
    return (
        <Router>
          <Switch>
            <Route path="/random">
              <RandomScreen />
            </Route>
          </Switch>
        </Router>
    )
}

经过一些调试后,我发现 let history = useHistory() 是导致此问题的原因,但我需要 useHistory 钩子

1 个答案:

答案 0 :(得分:1)

[build] exclude = [ "/README.md", "bash-script-buildpack" "issues" "infra" "docs" "docker-compose" "externalAuthServer" "important-sites.md" "build\." ] include = [ "microservice-a" "microservice-b" "microservice-c" "ui-app" ] 回调不能是异步的。首先定义异步函数然后调用它。 将其更改为:

useEffect