[英]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.