首页 > 解决方案 > 用于渲染应用程序的 ReactJS 逻辑

问题描述

所以我不是 React 最好的。我正在构建一个从外部端点获取用户信息并将其存储在本地存储中的应用程序。我意识到我的 react-app 在更新该数据的状态之前加载了 html,只是没有在前端显示它。我想让应用程序等到这些项目在渲染之前在本地存储中。有什么建议么?

标签: javascriptnode.jsreactjsexpresslifecycle

解决方案


使用功能组件,您通常会执行以下操作:

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>
}

推荐阅读