[英]React renders too much time - Which architecture should I choose?
我的問題:我正在嘗試使用 React 開發日歷應用程序。 我在左側菜單和右側有一個日歷:每天都有一個頁面。 用戶可以滑動到接下來的幾天(我使用 Swiper.js,每天一張幻燈片)。 URL 必須包含日期信息 (mysite.com/days/2020-12-05) 和日歷中突出顯示的當前日期。 我開發了一些可行的東西,但是白天頁面的渲染時間太長,而它們只需要渲染一次。
我的架構:
問題:我應該如何將日期參數從一個組件傳輸到另一個組件而不導致那些無用的重新渲染? I need that the URL, the left calendar and the slider day page are always synchronized wathever the user does: enters a new URL, select a date in the calendar or swipe from one day to an other.
我的代碼:(盡可能簡化)
應用程序.js
export default function App() {
const [date, setDate] = useState(0);
return (
<Router>
<div id="app_div">
<div id='left_menu'>
<ul>
// This is a simplified calendar: I can select 3 days and get the info of which date is currently selected
<li>
<Link to="/organisation/2020">2020</Link>
</li>
<li>
<Link to="/organisation/2021">2021</Link>
</li>
<li>
<Link to="/organisation/2022">2022</Link>
</li>
<li>
Current date: {date}
</li>
</ul>
</div>
<div id="right_frame">
<Switch>
<Route path="/Organisation/:day">
<Organisation setDate={setDate}></Organisation>
</Route>
<Route path="/Organisation">
<Organisation setDate={setDate}></Organisation>
</Route>
<Route path="/">
<Home />
</Route>
</Switch>
</div>
</div>
</Router>
);
}
組織.js
export default function Organisation(props) {
let { day } = useParams();
if (day === undefined) {
day = 2020;
}
return (
<Swiper
initialSlide="1"
onSlideChange={(swiper) => OnSlideChange(swiper, props.setDate)}
>
<SwiperSlide daynb={parseInt(day) - 1}><Day day={parseInt(day) - 1}></Day></SwiperSlide>
<SwiperSlide daynb={parseInt(day)}><Day day={parseInt(day)}></Day></SwiperSlide>
<SwiperSlide daynb={parseInt(day) + 1}><Day day={parseInt(day) + 1}></Day></SwiperSlide>
</Swiper>
);
}
function OnSlideChange(swiper, setDate) {
window.history.pushState(null, "New Page Title", "/organisation/" + swiper.slides[swiper.activeIndex].attributes.daynb.value);
setDate(swiper.slides[swiper.activeIndex].attributes.daynb.value);
}
代碼可在此處獲得 https://github.com/Toto5931/react-slides/tree/main/src
非常感謝 !!!
這就是 React 的工作方式 - 如果其中有任何更改,則重新渲染整個組件,但請記住,React 跟蹤 VDOM 中的更改,因此它非常快。
此外,您的App.js
只是一個Router
組件,所以說它“重新渲染整個應用程序”是誇大其詞。 它只重新渲染當前顯示的組件。
最后但同樣重要的是,看看shouldComponentUpdate
function,因為它可以為您節省一些重新渲染(例如,當您不需要從 API 獲取時)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.