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

Next.js传递useState作为Props报错:setSection不是函数

解决React父子组件传递setState方法报错:TypeError: setSection is not a function

问题场景

尝试从父组件向子组件传递状态section和对应的更新方法setSection,运行时触发错误:Unhandled Runtime Error TypeError: setSection is not a function。

父组件代码

export default function CareerProgression() {
   const [section, setSection] = useState< 'video' | 'condensed' | 'full' >('condensed');

   return (
      <ModuleToggle_withState section={section} setSection={setSection} />
   );
}

子组件代码

import { Dispatch, useEffect, SetStateAction } from 'react';

export function ModuleToggle_withState(section:any, setSection:Dispatch<SetStateAction<any>>) {
// 目前用any来测试传递useState props

   return (
      <>
         <SegmentedControl
            defaultValue='video'
            value={section}
            onChange={(value: 'video' | 'condensed' | 'full') => setSection(value)}
         />
      </> 
   ); 
}

错误原因

React组件的参数是单个props对象,而非独立的多个参数。当前子组件把section和setSection拆成两个参数,导致第一个参数实际接收的是完整的props对象(包含section和setSection两个属性),第二个参数setSection为undefined,调用时自然触发“不是函数”的错误。

修复方案

修改子组件,通过解构props对象获取需要的属性,并替换any为明确的类型定义:

import { Dispatch, SetStateAction } from 'react';

// 定义props类型,替代any获得类型检查
type ModuleToggleProps = {
  section: 'video' | 'condensed' | 'full';
  setSection: Dispatch<SetStateAction<'video' | 'condensed' | 'full'>>;
};

// 解构props对象获取section和setSection
export function ModuleToggle_withState({ section, setSection }: ModuleToggleProps) {
   return (
      <>
         <SegmentedControl
            defaultValue='video'
            value={section}
            onChange={(value) => setSection(value)}
         />
      </> 
   ); 
}

说明

  • 解构props是React组件接收参数的标准写法,确保能正确获取父组件传递的所有属性。
  • 替换any为联合类型后,TypeScript会提供类型校验,避免后续类型错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 14:30:51