我使用react上下文钩子为一个vite项目。下面是我使用的三个文件:
createContext
file:
import { createContext } from "react";
const SearchContext = createContext();
export default SearchContext;
contextProvider
file:
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;
主要文件:
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>
);
每当我运行npm run dev
,我的项目不渲染。如果我删除<SearchContextProvider>
组件,我的项目可以正常运行。
我做错了什么,或者我不能在我的网站项目中使用ContextHook ?请纠正我。
你在context组件中有两个错别字:
- 参数应该是
props
而不是childern
- 在JSX中应该是
props.children
而不是props.childern
const SearchContextProvider = (childern) => { // <-------- Should be props
const [state, dispatch] = useReducer(SearchReducer, INITIAL_STATE);
return (
<SearchContext.Provider
value={{
city: state.city,
dates: state.dates,
searchOption: state.searchOption,
dispatch,
}}>
{props.childern} {/* <--- Should be props.children */}
</SearchContext.Provider>
);
};
这里的变化是在SearchContextProvider组件中,我在返回的JSX周围添加了括号()。如果没有这些括号,函数体就变成了没有返回语句的代码块,这就是为什么你的应用程序可能不会像预期的那样呈现。