如果值为true,则尝试显示<BR/>组件,否则显示<Nothing/>组件。但是由于某种原因,尽管value是假的,<BR/>正在显示。
PC.js代码
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码
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
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/>组件时。
发布于 2022-06-20 09:56:32
当您执行localStorage.setItem("Value", value)时,它将将value注册为字符串。然后,当您调用const val = localStorage.getItem('Value')时,val将等于"false"。"false"是true,因为它是一个非空字符串。
要使此操作正常,在保存localStorage和JSON.stringify()值时,您应该使用它。如下所示:
注意到我注释了您的行,所以您可以看到我所做的更改。
// localStorage.setItem("Value", value);
localStorage.setItem("Value", JSON.stringify(value));// const val = localStorage.getItem('Value');
const val = JSON.parse(localStorage.getItem('Value'));https://stackoverflow.com/questions/72685115
复制相似问题