Vite项目使用React Context Hook无法渲染,请求排查修正
问题:Vite+React项目中使用Context Hook导致页面无法渲染
问题背景
在Vite+React项目中使用React Context Hook开发,添加<SearchContextProvider>组件后页面无法渲染,移除该组件则项目可正常运行,需排查并修正问题。
涉及代码
1. createContext文件
import { createContext } from "react"; const SearchContext = createContext(); export default SearchContext;
2. contextProvider文件
import { useReducer } from "react"; import SearchContext from "./SearchContext"; const INITIAL_STATE = { city: undefined, dates: [], searchOption: { adult: undefined, childern: undefined, rooms: undefined, }, }; const SearchReducer = (state, action) => { switch (action.type) { case "NEW_SEARCH": return action.playload; case "RESET_SEARCH": return INITIAL_STATE; default: return state; } }; const SearchContextProvider = (childern) => { const [state, dispatch] = useReducer(SearchReducer, INITIAL_STATE); return ( <SearchContext.Provider value={{ city: state.city, dates: state.dates, searchOption: state.searchOption, dispatch, }} > {props.childern} </SearchContext.Provider> ); }; export default SearchContextProvider;
3. 主文件
import React from "react"; import ReactDOM from "react-dom/client"; import App from "./App"; import "./index.css"; import { BrowserRouter } from "react-router-dom"; import SearchContextProvider from "./context/SearchContextState"; ReactDOM.createRoot(document.getElementById("root")).render( <React.StrictMode> <BrowserRouter> <SearchContextProvider> <App /> </SearchContextProvider> </BrowserRouter> </React.StrictMode> );
问题原因及修正方案
Vite项目完全支持React Context Hook,页面无法渲染是因为contextProvider文件存在多处语法和拼写错误:
- 组件参数错误:React组件接收的参数是
props,而非childern;渲染子组件时需使用props.children(注意拼写为children而非childern) - 拼写错误:
action.playload应为action.payload;searchOption中的childern应为children
修正后的contextProvider文件代码
import { useReducer } from "react"; import SearchContext from "./SearchContext"; const INITIAL_STATE = { city: undefined, dates: [], searchOption: { adult: undefined, children: undefined, // 修正拼写错误 rooms: undefined, }, }; const SearchReducer = (state, action) => { switch (action.type) { case "NEW_SEARCH": return action.payload; // 修正payload拼写 case "RESET_SEARCH": return INITIAL_STATE; default: return state; } }; // 修正组件参数为props const SearchContextProvider = (props) => { const [state, dispatch] = useReducer(SearchReducer, INITIAL_STATE); return ( <SearchContext.Provider value={{ city: state.city, dates: state.dates, searchOption: state.searchOption, dispatch, }} > {props.children} {/* 修正children拼写 */} </SearchContext.Provider> ); }; export default SearchContextProvider;
额外检查项
- 确认主文件中
SearchContextProvider的导入路径正确,确保./context/SearchContextState指向修正后的Provider文件 - 确保所有拼写错误已全部修正
修正后重新执行npm run dev,页面即可正常渲染。
内容的提问来源于stack exchange,提问作者kishor sutradhar
相关产品推荐
相关产品推荐

