React笔记本应用使用Context API访问Alert状态时触发TypeError报错的问题
Hey there! Let's break down why you're hitting that TypeError and how to fix it quickly.
Root Cause
The issue is in how you're passing values to your AlertContext.Provider in AlertState. Right now, you're using:
<AlertContext.Provider value={setMsg , alerts}>
This uses the comma operator, which evaluates each expression and returns only the last one—so your Context value is just the alerts state object, not an object containing both setMsg and alerts.
When you try to destructure const { alerts } = useContext(AlertContext) in your Alert component, you're trying to pull an alerts property from the alerts state object (which doesn't exist), resulting in undefined. Then accessing alerts.type throws the error.
Step-by-Step Fixes
Correct the Context Provider Value
WrapsetMsgandalertsin an object so both are available via the Context:// In AlertState.js return ( <AlertContext.Provider value={{ setMsg, alerts }}> {props.children} </AlertContext.Provider> );Add Conditional Rendering to the Alert Component
Whenalerts.messageisnull(like after the timeout), you don't want to render an empty alert box. Add a check to skip rendering in that case:// In Alert.js export const Alert = (props) => { const { alerts } = useContext(AlertContext); // Don't render anything if there's no message if (!alerts.message) return null; return ( <div> <div className={`alert alert-${alerts.type} alert-dismissible fade show`} role="alert"> {alerts.message} </div> </div> ); };Ensure Your App is Wrapped in AlertState
Double-check that your root component (or the components that need access to the Alert Context) are wrapped insideAlertState. For example:// In App.js import AlertState from './context/notes/AlertState'; import { Alert } from './components/Alert'; function App() { return ( <AlertState> {/* Your app content here */} <Alert /> {/* Other components like Login, Notebook, etc. */} </AlertState> ); }
How It Works Now
- The Context Provider now passes an object with both
setMsg(to update alerts) andalerts(the current state). - Your Alert component correctly destructures the
alertsstate from the Context, and only renders when there's a message to show. - When you call
setMsgafter a user action (like logging in), the state updates, the Alert component re-renders with the correct message and type, and disappears after 1.5 seconds as expected.
内容的提问来源于stack exchange,提问作者Sushanth

