[英]How to prevent automatic render when state changed by some other component that uses React Context API?
我正在使用Context API進行響應。 在上下文中,我有一個名為isAuthenticated的屬性,該屬性在App.js中用於路由目的。 但是問題是,當操作isAuthenticated屬性時,該App.js文件也會重新渲染。 而且我不想這種行為。
即使該數據更改或狀態被其他組件更改,如何防止該組件自動重新呈現。
我認為React.memo是我的選擇,這是正確的解決方案嗎?
我的路由配置:
<HashRouter>
<Switch>
<Route exact path="/" render={() => <Redirect to="/app/dashboard" />} />
<Route
exact
path="/app"
render={() => <Redirect to="/app/dashboard" />}
/>
<PrivateRoute path="/app" component={Layout} />
<PublicRoute path="/login" component={Login} />
<Route component={Error} />
</Switch>
</HashRouter>
基於來自Context API的isAuthenticated值的公共和私有路由
function PrivateRoute({ component, ...rest }) {
console.log(isAuthenticated)
return (
<Route
{...rest}
render={props =>
isAuthenticated ? (
React.createElement(component, props)
) : (
<Redirect
to={{
pathname: "/login",
state: {
from: props.location,
},
}}
/>
)
}
/>
);
}
function PublicRoute({ component, ...rest }) {
console.log(isAuthenticated)
return (
<Route
{...rest}
render={props =>
isAuthenticated ? (
<Redirect
to={{
pathname: "/",
}}
/>
) : (
React.createElement(component, props)
)
}
/>
);
}
}
在狀態改變后阻止組件渲染不是一個好方法,因為這種情況不適合React環境的邏輯。
我認為您應該更改應用程序業務邏輯。 我建議您檢查“ 原子設計方法” 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.