You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中useReducer+Context传值时state返回undefined问题求助

解决Context传递搜索状态返回undefined的问题

你遇到的问题由三个核心错误导致,以下是具体修复方案:

1. useReducer的Reducer函数参数顺序颠倒

Reducer函数的正确签名是(state, action) => newState,你写反了参数顺序,导致状态无法正确更新。

修改searchcontext.js中的reducer函数:

// 原错误代码
const searchReducer = (action, state) => {
  switch (action.type) {
    case "NEW_SEARCH":
      return action.payload;
    case "RESET_SEARCH":
      return INITIAL_STATE;
    default:
      return state;
  }
};

// 修改后
const searchReducer = (state, action) => { // 交换state和action的顺序
  switch (action.type) {
    case "NEW_SEARCH":
      return action.payload;
    case "RESET_SEARCH":
      return INITIAL_STATE;
    default:
      return state;
  }
};

2. Context Provider未暴露完整state对象(或解构方式错误)

你在hotel.jsx中试图解构state,但SearchContext.Provider的value里并没有直接提供state属性,而是拆分了city、dates、options单独暴露。

方案一:修改Provider的value,暴露完整state

在searchcontext.js的Provider中添加state属性:

<SearchContext.Provider
  value={{
    state, // 新增这一行,暴露整个state对象
    city: state.city,
    dates: state.dates,
    options: state.options,
    dispatch,
  }}
>
  {children}
</SearchContext.Provider>

方案二:直接解构需要的属性(更推荐)

在hotel.jsx中直接获取需要的字段,而不是解构state:

// 原错误代码
const {state}= useContext(SearchContext);
console.log(state);

// 修改后
const { city, dates, options } = useContext(SearchContext);
console.log(city, dates, options);

3. Dispatch的Payload字段不匹配INITIAL_STATE

你在header.jsx中dispatch的payload用了destination字段,但INITIAL_STATE里对应的是city,这会导致更新后的state没有city属性,而是多了destination,进而Context中的city始终为undefined。

修改header.jsx中的handleSearch函数:

// 原错误代码
dispatch({type:"NEW_SEARCH",payload:{destination,dates,options}});

// 修改后
dispatch({type:"NEW_SEARCH",payload:{city: destination, dates, options}}); // 将destination改为city

完成以上修改后,hotel.jsx就能正确获取到Context中的搜索状态了。

内容的提问来源于stack exchange,提问作者Adem Sghaier

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 19:45:39