[英]How to use useState inside a react functional component which is async
My App
is a functional component which is declared async
because I have to fetch data from the server before view is rendered and the code is as follows我的
App
是一个声明为async
的功能组件,因为我必须在呈现视图之前从服务器获取数据,代码如下
import React,{useState} from "react";
import DashBoard from './components/DashBoard'
const axios = require('axios')
const App = async props => {
const allDashBoardsList = await axios.get('http://localhost:9000/getAllDashBoardNames')
const [dashboard,setDashboard] = useState(allDashBoardsList.data[0].dashboard)
const handleDashboardChange = e => {
setDashboard(e.target.value)
}
return (
<>
<select>
{allDashBoardsList.data.map(e => <option value={e.dashboard} onChange = {handleDashboardChange} > {e.dashboard} </option>)}
</select>
<DashBoard dashboard={dashboard} />
</>
)
}
export default App
and my index.js is like this,而我的 index.js 是这样的,
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
App().then(e => {
ReactDOM.render(e, document.getElementById('root'));
})
Everything works fine without any error when i return just <h1> Hello </h1>
from App
but I am getting当我从
App
返回<h1> Hello </h1>
时,一切正常,没有任何错误,但我得到
Unhandled Rejection (Error): Invalid hook call. Hooks can only be called inside of the body of a function component
when I use useState
to set the state当我使用
useState
设置状态时
is there any way to counter this or should I have to use a class component
with UNSAFE_componentWillMount
有什么办法可以解决这个问题,或者我是否应该使用带有
UNSAFE_componentWillMount
的class component
Try wrapping your async call in the useEffect hook instead and setting an acceptable default state尝试将异步调用包装在 useEffect 挂钩中并设置可接受的默认状态
const App = props => {
const [dashboard,setDashboard] = useState('placeholder default state');
useEffect(() => {
const fetchData = async () => {
const result = await axios.get('http://localhost:9000/getAllDashBoardNames');
setDashboard(allDashBoardsList.data[0].dashboard);
};
fetchData();
}, []);
const handleDashboardChange = e => {
setDashboard(e.target.value)
}
return (
<>
<select>
{allDashBoardsList.data.map(e => <option value={e.dashboard} onChange = {handleDashboardChange} > {e.dashboard} </option>)}
</select>
<DashBoard dashboard={dashboard} />
</>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.