【问题标题】:react context ternary operator returning true value all the time反应上下文三元运算符一直返回真值
【发布时间】:2020-11-10 05:08:32
【问题描述】:

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

let theme=AdminContext.AdminTheme;

theme ? 'dark' : 'light'

console.log(theme) 返回 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>
);
}
}`

【问题讨论】:

  • 你能显示实际代码吗?

标签: javascript reactjs


【解决方案1】:

存储在本地存储中的项目是 JSON 字符串,因此在获取/检索时需要对其进行解析。 “真”和“假”都是真值。

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

在浏览器控制台中试用

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

【讨论】:

    猜你喜欢
    • 2018-01-26
    • 2021-09-09
    • 1970-01-01
    • 2014-08-03
    • 1970-01-01
    • 2014-09-24
    • 1970-01-01
    • 2020-02-09
    • 2020-08-02
    相关资源
    最近更新 更多