javascript - 用于渲染应用程序的 ReactJS 逻辑
问题描述
所以我不是 React 最好的。我正在构建一个从外部端点获取用户信息并将其存储在本地存储中的应用程序。我意识到我的 react-app 在更新该数据的状态之前加载了 html,只是没有在前端显示它。我想让应用程序等到这些项目在渲染之前在本地存储中。有什么建议么?
解决方案
使用功能组件,您通常会执行以下操作:
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>
}
推荐阅读
- firebase - 带有关于 pubsub 主题的消息的 Firebase 模拟器未触发云功能
- javascript - JS:基于屏幕宽度的条件图片链接
- javascript - React.js - 具有延迟和防闪烁的加载指示器
- java - 带有 Stream 的 Spring JPA 存储库
- python - 如何在 Tkinter Text Widget 中打印 Dictionary 的项目?
- time - 在 simulink 中设置控制循环时间
- merge - 如何在 Bitbucket 上进行合并请求?
- python - 检查 10 个不同集合之间的共同元素
- kotlin - 更改列表中列表元素的值 Kotlin 错误
- reactjs - 错误:对象作为 React 子对象无效(找到:带有键 {name} 的对象)。如果您打算渲染一组孩子,请改用数组