[英]Error: Invalid hook call. Hooks can only be called inside of the body of a function component. - React
So I'm trying to declare a state then make an API call then set the state but I'm encountering 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:
所以我试图声明一个 state 然后进行 API 调用然后设置 state 但我遇到
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:
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:
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:
Error. 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:
错误。 I have checked my react version and react dom and it is fine and I do not have two copies of React.我已经检查了我的 react 版本和 react dom,这很好,我没有两个 React 副本。 Here is a simplified version of my code:
这是我的代码的简化版本:
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应用程序.js
function App(){
return (
<Router>
<Switch>
<Route path="/random">
<RandomScreen />
</Route>
</Switch>
</Router>
)
}
After some debugging I found out that let history = useHistory()
is the cause of this problem but I need useHistory
hook经过一些调试,我发现
let history = useHistory()
是这个问题的原因,但我需要useHistory
钩子
useEffect
callback cannot be async. useEffect
回调不能是异步的。 First define the async function then call it.首先定义异步 function 然后调用它。 Change this to:
将其更改为:
useEffect( () => {
async function apiCall() {
// Make API call
}
apiCall()
.then(function(response){
setState(response.data)
})
},[])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.