[英]Mapping through local JSON file with large data in react takes some time to load. How to fix it?
I am using react with TypeScript.我正在使用与 TypeScript 的反应。 I am mapping through a JSON file in react.我正在通过 JSON 文件进行映射。 It takes a second to render all the data in the browser.在浏览器中呈现所有数据需要一秒钟。 I'm using functional components.我正在使用功能组件。 Here is the code.这是代码。 Please help me optimize the render time in the browser.请帮我优化浏览器中的渲染时间。
import users from "../data/users.json";
const Users:React.FC=() => {
const displayUsers=users.map((item){
return(
<p> {item.username} </p>
<p> {item.location} </p>
<img src={item.avatar}/>
)
})
return(
<div className='container'>
<div className='user'>
{displayUsers}
</div>
</div>
)
}
Issue: With your current implementation, users.map
will be executed at each render of the component.问题:使用您当前的实现, users.map
将在组件的每次渲染时执行。
You can optimize it using useMemo
hook:您可以使用useMemo
挂钩对其进行优化:
import users from "../data/users.json";
const Users:React.FC = () => {
const mappedUsers = useMemo(() => {
return users.map((item) => {
return( <>
<p> {item.username} </p>
<p> {item.location} </p>
<img src={item.avatar}/>
</> )
})
}, [])
return(
<div className='container'>
<div className='user'>
{mappedUsers}
</div>
</div>
)
}
Now the map
function will be called only once when component mounts.现在map
function 将在组件安装时仅调用一次。
If you want to re-calculate the data using map
based on some dependency change, you can put it in dependency array []
of useMemo
.如果你想基于一些依赖变化使用map
重新计算数据,你可以把它放在useMemo
的依赖数组[]
中。
If users
data is comping through props
of some parent component, you can use React.memo
to avoid re-rendering of (this) child component when props
are same.如果users
数据是通过某些父组件的props
进行的,您可以使用React.memo
来避免在props
相同时重新渲染 (this) 子组件。 Here is a related post with demo for React.memo
.这是React.memo
演示的相关帖子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.