![](/img/trans.png)
[英]React hooks: Parent component not updating when dispatch is called in a child component
[英]React context api dispatch does not dispatch values when called when called
我正在使用 reactjs 创建一个应用程序,并且我使用上下文 api 作为我的 state 管理工具
但调度不调度值
即使在调用调度后,城市仍显示未定义。
搜索上下文
在这里,我创建了初始 state,其中城市未定义,日期为空数组,选项值在初始 state 上未定义
我只有两个动作搜索和重置动作,当用户单击按钮时应该调度它们
import { useReducer } from "react"
import { createContext } from "react"
const INITIAL_STATE = {
city: undefined,
dates: [],
options: {
adult: undefined,
children: undefined,
room: undefined,
}
}
export const SearchContext = createContext(INITIAL_STATE)
const SearchReducer = (state, action) => {
switch (action) {
case "NEW_SEARCH":
return action.payload;
case "RESET_SEARCH":
return INITIAL_STATE;
default:
return state
}
}
export const SearchContextProvider = ({ children }) => {
const [state, dispatch] = useReducer(SearchReducer, INITIAL_STATE)
return (
<SearchContext.Provider
value={{ city: state.city, dates: state.dates, options: state.options, dispatch }}>
{children}
</SearchContext.Provider>
)
}
index.js
我用我的 searchcontext 提供程序包装了整个应用程序,以便我可以访问传递给所有组件的值
import App from './App';
import { SearchContextProvider } from './context/SearchContext';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<SearchContextProvider>
<App />
</SearchContextProvider>
</React.StrictMode>
);
header.js
import { useContext } from "react";
import { SearchContext } from "../../context/SearchContext";
const Header = () => {
const { dispatch } = useContext(SearchContext)
const handleSearch = (e, dispatch) => {
dispatch({ type: "NEW_SEARCH", payload: { destination, "dates": "14-may-2122", options } })
navigate("/hotels", { state: { destination, dates, options } });
};
return (
<div className="header">
<button className="headerBtn" onClick={(e) => handleSearch(e, dispatch)}>
Search
</button>
</div>
)
}
你忘了.type
const SearchReducer = (state, action) => {
switch (action.type) { // <--- add `.type` here
case "NEW_SEARCH":
return action.payload;
case "RESET_SEARCH":
return INITIAL_STATE;
default:
return state
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.