react上下文三元运算符始终返回真值



该代码用于将主题存储在localstorage dark或light中。

let theme=AdminContext.AdminTheme;
theme ? 'dark' : 'light'

console.log(主题(返回false;但只有黑暗的被退回

console.log(typeof(theme((返回布尔

那么可能出了什么问题

我试着直接给出false作为工作正常的参数。。

我刚开始反应,所以如果你有任何其他建议,请帮助我

提前知道伙计们

App.js

`let theme=AdminContext.AdminTheme;
console.log(theme)
return (
<div className={`App ${theme ? 'dark' : 'light'}`}>
<Router basename='/reactadmin'>
<Switch>
<PublicRoute exact path='/(login)' component={AdminLogin}/>
<PrivateRoute component={PrivateRoutes} value={state} setState= 
{setState}/>
<Route path="*" component={NotFoundPage}/>
</Switch>

</Router>

</div>

上下文

`import React from 'react';
export default React.createContext({
AdminId:localStorage.getItem('adminid') || null,
AdminName:localStorage.getItem('adminname') || null,
AdminType:localStorage.getItem('admintype') || null,
AdminToken:localStorage.getItem('admintoken') || null,
AdminUser:localStorage.getItem('adminuser') || null,
AdminProfile:localStorage.getItem('adminprofile') || null,
AdminProfile:localStorage.getItem('admintheme') || false,
removeAdminData: ()=>{},
Authenticate: ()=>{},
changeToken:(newToken)=>{},
setAdminData:(admindata)=>{},
toggleAdminTheme:()=>{}
});`

上下文的全局状态

state={
AdminId:localStorage.getItem('adminid') || null,
AdminName:localStorage.getItem('adminname') || null,
AdminType:localStorage.getItem('admintype') || null,
AdminToken:localStorage.getItem('admintoken') || null,
AdminUser:localStorage.getItem('adminuser') || null,
AdminProfile:localStorage.getItem('adminprofile') || null,
AdminTheme:localStorage.getItem('admintheme') || false,
}
toggleAdminTheme=()=>{
localStorage.setItem('admintheme',!this.state.AdminTheme);
this.setState({
AdminTheme:!this.state.AdminTheme,
});
}
render(){
return(
<AdminContext.Provider
value={{
AdminId: this.state.AdminId,
AdminName: this.state.AdminName,
AdminType:this.state.AdminType,
AdminToken:this.state.AdminToken,
AdminUser:this.state.AdminUser,
AdminProfile:this.state.AdminProfile,
AdminTheme:this.state.AdminTheme,
setAdminData:this.setAdminData,
removeAdminData:this.removeAdminData,
Authenticate:this.Authenticate,
changeToken:this.changeToken,
toggleAdminTheme:this.toggleAdminTheme,
}}
>
{this.props.children}
</AdminContext.Provider>
);
}
}`

存储在本地存储中的项是JSON字符串,因此在提取/检索时需要对其进行解析。两个";真";以及";false";是真实的价值观。

state={
...
JSON.parse(AdminTheme:localStorage.getItem('admintheme')) || false,
}

在浏览器控制台中试用

localStorage.setItem('test', false);
localStorage.getItem('test'); // "false"
JSON.parse(localStorage.getItem('test')); // false

最新更新