Next.js集成Material UI Drawer时useState无法正常工作的求助
Hey there, let's get that useState problem sorted out. From what you've shared, there are a few common culprits we can check first—most of these are easy fixes that don't require messing with webpack.
First: Fix the React Import Case
Looking at your Nav.jsx code, you've got:
import React, { useState } from 'React'
This is a sneaky mistake! React's package name is lowercase 'react', not uppercase. Next.js (and React in general) treats 'React' as a different module, which can break hook calls because React won't recognize the component context correctly. Update that line to:
import React, { useState } from 'react'
Second: Fix the Undefined user Variable in Drawer
In your Drawer.jsx, you're referencing user.userName but never defined the user variable. This throws a runtime error that might make it seem like useState isn't working (since the component crashes before it can update state).
Either define the user variable (e.g., pass it as a prop to the Drawer, or initialize it with a default value):
// Add this at the top of your Drawer component, or pass user as a prop const user = { userName: "Guest" }; // Example default
Or update the item to use a hardcoded value temporarily to test:
{ text: "Guest", icon: <AccountCircleIcon /> },
Third: Clear Dependencies and Cache
If the above fixes don't work, let's rule out corrupted dependencies or cached data:
- Delete your
node_modulesfolder - Delete
package-lock.json(oryarn.lockif you use Yarn) - Run
npm install(oryarn install) to reinstall dependencies - Restart your Next.js dev server, and hard-refresh your browser (Ctrl+Shift+R) to clear client-side cache
Fourth: Double-Check Hook Usage Rules
You mentioned you imported useState correctly, but just to confirm:
- Make sure
useStateis called at the top level of yourNavcomponent (you're doing this right—good job!) - Never call hooks inside conditionals, loops, or nested functions (your code avoids this, so that's not the issue here)
Why You Don't Need to Touch Webpack
Most of the time, you don't need to modify webpack config in Next.js for basic React hook issues. The fixes above should resolve your problem without going down that road.
Modified Code Snippets
Here's the corrected Nav.jsx import line:
import React, { useState } from 'react'
And a quick fix for Drawer.jsx to avoid the user error:
function Drawer({isOpened}) { // Add a default user object const user = { userName: "Your Name" }; const items = [ { text: user.userName, icon: <AccountCircleIcon /> }, // ... rest of your items ] // ... rest of the component }
Give these steps a try—odds are the first two fixes will get your useState working again with the Drawer.
内容的提问来源于stack exchange,提问作者S.M

