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

使用同一SearchInputContext的组件报错,是否必须新建Context?

问题解答

错误原因

你遇到的Uncaught TypeError: object is not iterable错误根本不是因为两个组件共用同一个Context,而是解构方式错误:

  • Places组件使用对象解构const {postCode, setPostCode } = useContext(...)是正确的,因为你在Provider中传递的value是一个对象。
  • 但FilterOption组件错误地使用了数组解构const [price, setPrice...] = useContext(...),对象无法通过数组方式解构,因此触发了迭代错误。

简便解决方法

完全不需要新建Context,直接将FilterOption里的解构改为对象解构即可:

const FilterOption = () => {
    const { price, setPrice, bedroomCount, setBedroomCount, bathroomCount, setBathroomCount, parkingCount, setParkingCount }
     = useContext(SearchInputContext);
}

什么时候需要新建Context?

只有当状态集合属于完全独立的业务模块,或者需要在不同组件树分支中隔离状态时,才需要考虑拆分Context:

  • 若搜索地址和筛选条件是完全独立的业务逻辑,且后续可能被不同组件树使用,拆分Context更合理。
  • 若两者都是搜索栏的关联状态,共用同一个Context完全没问题,反而便于统一管理。

补充优化建议

可以将Context中的状态按逻辑分组,让结构更清晰:

export const SearchInputProvider = ({ children}) => {
    const [postCode, setPostCode] = useState();
    const [price, setPrice] = useState();
    const [bedroomCount, setBedroomCount] = useState();
    const [bathroomCount, setBathroomCount] = useState();
    const [parkingCount, setParkingCount] = useState();
       
    return (
        <SearchInputContext.Provider value={{
            // 地址相关状态
            location: { postCode, setPostCode },
            // 筛选条件相关状态
            filters: {
                price, setPrice,
                bedroomCount, setBedroomCount,
                bathroomCount, setBathroomCount,
                parkingCount, setParkingCount
            }
        }}>
            {children}
        </SearchInputContext.Provider>
    )
}

组件中解构时也会更直观:

// Places组件
const { location: { postCode, setPostCode } } = useContext(SearchInputContext);

// FilterOption组件
const { filters: { price, setPrice, bedroomCount, setBedroomCount } } = useContext(SearchInputContext);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 21:33:20