通过Context.Provider传递setState函数报错问题排查
解决方案:DisplayContext未定义错误修复
问题根源
子组件Preset中使用了DisplayContext但未导入,同时父组件未导出该Context,导致浏览器抛出Uncaught ReferenceError: DisplayContext is not defined错误。
修复步骤
导出父组件中的DisplayContext
在Game组件中,将创建的Context导出,让子组件可以导入使用:import React from "react"; import { createContext, useState } from "react"; import Header from './Header' import Display from './Display' // 导出DisplayContext export const DisplayContext = createContext(null); export default function Game() { const [display, setDisplay] = useState('custom_background'); const [isGameComplete, setIsGameComplete] = useState(false); return ( <DisplayContext.Provider value={setDisplay}> {!display.includes('game_over') && <Header />} <Display display={display} /> </DisplayContext.Provider> ) }在子组件中导入DisplayContext
在Preset组件顶部添加Context的导入语句(注意路径需根据实际文件结构调整,比如如果Preset在Display子目录下,路径应为../Game):import React from 'react' import { useContext } from 'react'; // 导入DisplayContext import { DisplayContext } from './Game'; const imagePresetFiles = import.meta.glob('../../assets/*.jpg') console.log(imagePresetFiles) export default function Preset({defaultBackground, backgrounds, setBackgrounds}) { const setDisplay = useContext(DisplayContext); console.log("Preset useContext", setDisplay) function handleSubmit(event) { event.preventDefault(); setDisplay('custom_difficulty_options'); } function handleChange(event) { setBackgrounds([...backgrounds, event.target.value]); } function handleClear() { setBackgrounds([defaultBackground]); } return ( <div> <form onSubmit={handleSubmit}> <section> <input type="file" multiple onChange={handleChange}/> <div> <section></section> <section></section> </div> </section> <section> <h2>NOTE:</h2> <div> <p>File must be in the .gif, .svg, .jpeg, or .png format</p> <p>Multiple images added will be rotated each round</p> </div> <button onClick={handleClear}> Clear Choices </button> <button> Confirm Choices </button> </section> </form> {backgrounds.map((background, index) => { return <img src={background} alt={background} key={index} /> })} </div> ) }
额外注意事项
- 确认
Preset组件是DisplayContext.Provider的后代组件,只有在Provider包裹范围内的组件才能通过useContext获取到Context值。 - 检查导入路径是否正确,避免因路径错误导致的模块未找到问题。
内容的提问来源于stack exchange,提问作者Felt_Notebook
相关产品推荐
相关产品推荐

