所以我对React并不是最好的。我正在构建一个从外部端点获取用户信息并将其存储在本地存储中的应用程序。我意识到我的react-app在数据状态更新之前正在加载html,只是没有在前端显示它。我想让应用程序等到这些项目在本地存储中再渲染。有什么建议吗?
您可以使用异步并等待它。
async componentDidMount(){
await fetch()....
/* your code goes here*/
}
使用功能组件,您通常会执行以下操作:
function App() {
const [data, setData] = useState(null)
useEffect(() => {
// Fetching or other async logic here...
fetch('/some/url/here')
.then(response => response.json())
.then(data => setData) // save the result in state
}, [])
// Not loaded yet, return nothing.
if (!data) {
return null
}
// Loaded! return your app.
return <div>Fetched data: { data.myData }</div>
}