React中使用setState无法修改test变量值的问题求助
test Remains Stuck as false Hey there! The problem you're running into is that your <Nav.Link> components are using the native href attribute, which triggers a full page refresh every time you click them. When the page refreshes, your entire App component re-mounts, resetting the test state back to its initial value of false—that's why your state updates seem to have no effect.
Here's how to fix this properly, using React Router's navigation tools to keep your app in single-page mode (no full refreshes) while updating the state:
Step 1: Wrap Your App in a Router
First, make sure your app is wrapped in a React Router component so you can use navigation hooks. Update your App.js:
import { useState } from 'react'; import { BrowserRouter as Router } from 'react-router-dom'; import myNavBar from './myNavBar'; import Test from './Test'; // Ensure your Test component is imported function App() { const [test, setTest] = useState(false); return ( <Router> <div className="App"> <myNavBar handleTest={(value) => setTest(value)} /> <div> {test ? <Test /> : null} </div> </div> </Router> ); } export default App;
Step 2: Update the Navbar to Use React Router Navigation
Modify your myNavBar.js to use the useNavigate hook instead of native href links. This lets you navigate without refreshing the page, so your state stays intact:
import { Navbar, Nav } from 'react-bootstrap'; import { useNavigate } from 'react-router-dom'; const myNavBar = (props) => { const navigate = useNavigate(); const handleTest = (value) => { // Update the parent state first props.handleTest(value); // Navigate to the correct route without a page refresh navigate(value ? '/test' : '/'); }; return ( <> <Navbar bg="white"> <Navbar.Brand>Test</Navbar.Brand> <Nav> {/* Remove href and use onClick to trigger our handler */} <Nav.Link onClick={() => handleTest(false)}>Home</Nav.Link> <Nav.Link onClick={() => handleTest(true)}>Test</Nav.Link> </Nav> </Navbar> </> ); }; export default myNavBar;
Why This Works
- By removing the
hrefattribute, we prevent the browser from triggering a full page reload when the link is clicked. - The
useNavigatehook from React Router handles navigation within the single-page app, so your component tree and state remain preserved. - We update the
teststate before navigating, ensuring the state change is reflected immediately.
Optional: Preserve Semantics for Accessibility
If you want to keep the href attribute for accessibility reasons (like screen reader support), you can add it back but prevent the default browser behavior:
<Nav.Link href="/" onClick={(e) => { e.preventDefault(); // Stop the native page refresh handleTest(false); }} >Home</Nav.Link>
内容的提问来源于stack exchange,提问作者Tom

