首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >localStorage正在更新,但面对输出的问题,false被解释为true。

localStorage正在更新,但面对输出的问题,false被解释为true。
EN

Stack Overflow用户
提问于 2022-06-20 09:46:47
回答 1查看 44关注 0票数 1

如果值为true,则尝试显示<BR/>组件,否则显示<Nothing/>组件。但是由于某种原因,尽管value是假的,<BR/>正在显示。

PC.js代码

代码语言:javascript
复制
import React,{useContext, useState} from 'react'
import { BRcontext } from "../App";
import './Profile.css';
import { useNavigate } from "react-router-dom"

export default function Profile() {
   const [value, setValue] = useState(false);
   localStorage.setItem("Value", value);
   console.log(value);
   const navigate = useNavigate();
   return (
       <div>
           <div className='container mt-5'>
               <div className='row'>
                   <div>
                       <h3 className='mt-5'>Send Request</h3>
                       <button className='btn btn-success mt-3 ps-3 pe-3' onClick={() => {setValue(true)}}>Request</button>
                   </div>
               </div>
           </div>
       </div>
   )
}

BR1.js码

代码语言:javascript
复制
import React, { useContext } from "react";
import BR from "./BR";
import Nothing from './Nothing'

export default function BR1() {
    const val = localStorage.getItem('Value');
  return (
    <div>
      {console.log(val)}
      {val ? <BR/> : <Nothing/>}
    </div>
  );
}

BR.js

代码语言:javascript
复制
import React from 'react'
import './Profile.css';

export default function BR() {
    let values = false;
    return (
        <div>
            <div className='container mt-5'>
                <div className='row'>
                    <div>
                        <h3 fontSize="150px">Do you want to be a ....?</h3>
                        <button type="button" className="btn btn-success ml-5 mt-3 mr-1">YES</button>
                        <button type="button" className="btn btn-danger ms-5 mt-3 mr-1"  onClick={() => {localStorage.removeItem('Value')}}>NO</button>
                    </div>
                </div>
            </div>
        </div>
    )
}

localStorage中的值正在正确更新,而val也正在更新,但如果<BR/>false,则仍然显示在需要<Nothing/>组件时。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-06-20 09:56:32

当您执行localStorage.setItem("Value", value)时,它将将value注册为字符串。然后,当您调用const val = localStorage.getItem('Value')时,val将等于"false""false"true,因为它是一个非空字符串。

要使此操作正常,在保存localStorageJSON.stringify()值时,您应该使用它。如下所示:

注意到我注释了您的行,所以您可以看到我所做的更改。

代码语言:javascript
复制
// localStorage.setItem("Value", value);
localStorage.setItem("Value", JSON.stringify(value));
代码语言:javascript
复制
// const val = localStorage.getItem('Value');
const val = JSON.parse(localStorage.getItem('Value'));
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72685115

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档