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

如何使用createContext设置数据、存入state数据及解决参数报错问题

问题1:createContext 报错“Expected 1 arguments, but got 0”

报错原因

你当前使用的是 TypeScript 开发环境,createContext 是 强类型 API,必须传入 默认初始值,或者显式声明 Context 类型后配合类型断言使用。

修复方案

先定义 Context 的数据类型,再创建 Context,推荐传入符合类型的默认值避免运行时报错:

// 定义Context包含的数据类型,可根据你的实际业务字段调整具体类型
type LastChanceContextType = {
  lastChances: any[],
  lastChance: Record<string, any>
}

// 传入默认值创建Context,类型匹配即可
export const LastChanceContext = createContext<LastChanceContextType>({
  lastChances: [],
  lastChance: {}
})

如果确实不想写默认值,可以用类型断言绕开校验(不推荐,未被Provider包裹的组件调用Context会出现空值报错):

export const LastChanceContext = createContext<LastChanceContextType>(null as unknown as LastChanceContextType)

问题2:createContext 数据设置、state 存入数据的实现

实现逻辑

你已经采用 useReducer 做状态管理,Context 仅作为状态传递的通道:所有数据修改都通过 dispatch 触发 reducer 函数更新 state,state 变化后会自动同步给 Context.Provider 的 value,下游组件直接取 Context 里的值即可。

现有代码修复

你当前的 dispatch 调用写法错误,useReducer 的 dispatch 仅接收 action 对象作为参数,不需要额外包裹 state,修改步骤如下:

1. 补充正确的reducer逻辑

const lastChanceReducer = (state: LastChanceContextType, action: {type: string, payload: any}) => {
  switch(action.type) {
    case GET_LASTCHANCE:
      // 把接口返回的列表存入state的lastChances字段,实现state更新
      return {
        ...state,
        lastChances: action.payload
      }
    default:
      return state
  }
}

2. 修正useEffect里的dispatch调用

if(Object.keys(result).length !== 0) {
  // 直接传入action对象即可,不需要包裹state
  dispatch(action)
  console.log(result.data.data.lastChanceList);
}

3. 下游组件取值示例

被 LastChanceWrapper 包裹的子组件,直接通过 useContext 即可拿到最新的状态:

import { useContext } from 'react'
import { LastChanceContext } from '你存放Context的文件路径'

const DemoChild = () => {
  const { lastChances } = useContext(LastChanceContext)
  // 直接使用lastChances渲染即可,state更新时会自动触发组件重渲染
  return <div>{lastChances.map(item => <div key={item.id}>{item.title}</div>)}</div>
}

小优化:children 的类型建议用 React.ReactNode 替代 any,类型更安全。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 08:54:01