反应回调onClick无法调用可能是“未定义”的对象

时间:2019-01-14 17:52:58

标签: reactjs typescript types

下面是我的父组件,它处理应用程序的state

 function App() {   
    const [teamData, setTeamData] = useState<any | undefined>(undefined);
    return(
      <> 
          <Teams teams={teams} onTeamClick={() => setTeamData(team)} />
          <Modal teamData={teamData} />
      </>
    )
}

接下来是我的组件,它将状态传递回树。但是,我收到以下打字稿错误:

  

无法调用可能是“未定义”的对象。

type Props = {
   teams: any[];
   onTeamClick: () => void;
}

function Teams({teams, onTeamClick}: Props) {
   return(
     <div>
       {teams.map(team => {
         // the error is coming from onTeamClick
         // No error if I change it to onTeamClick={onTeamClick}
         <Team name={team.name} onTeamClick={() => onTeamClick(team)} />
       })
     </div>
   )
}

2 个答案:

答案 0 :(得分:2)

那是因为这里:

<Teams teams={teams} onTeamClick={() => setTeamData(team)} />

您从无处获取team变量,因此它是undefined

这样做应该没问题:

<Teams teams={teams} onTeamClick={ team => setTeamData(team) } />

我对React Hooks并不超级熟悉,但是我认为您也许可以这样做,但时间要短一些:

<Teams teams={teams} onTeamClick={ setTeamData } />

答案 1 :(得分:0)

它是undefined,因为挂钩的初始状态使编译器认为它可能是undefined

尝试一下吗?

<Team name={team.name} onTeamClick={() => onTeamClick && onTeamClick(team)} />