React中函数为useState变量赋值报错:setJobStart is not a function
报错原因
setJobStart 是你在 App 组件内声明的状态更新函数,没有正确传递到最终调用它的 ArrivedOk 函数里,所以调用时提示未定义,一共漏了三个传递环节:
- 父组件
App渲染ActionButtons时,没有把内部的setJobStart、startJob等状态通过 props 传给子组件 ActionButtons组件没有在入参中接收setJobStart这个props,调用ArrivedOk时也没有传入需要的参数ArrivedOk定义时要求第一个入参是setJobStart,但实际调用时是空参,自然获取不到这个函数
修正方案
方案1:按现有逻辑补全参数传递
- 修正 App 组件代码,把状态和更新函数传给子组件:
function App(){ const [arrived, setArrived ] = useState(false); const [startJob, setJobStart ] = useState(false); return( <ActionButtons arrived={arrived} startJob={startJob} setJobStart={setJobStart} setArrived={setArrived} /> ) }
- 修正 ActionButtons 组件代码,接收props并给ArrivedOk传参:
function ActionButtons ({arrived, startJob, setJobStart, setArrived, dialer, directions}) { return( <Button title="Arrived" disabled={arrived} onPress={() => ArrivedOk(setJobStart, setArrived)} buttonStyle={{ backgroundColor: '#0b77b0' }} /> )}
- 修正 ArrivedOk 函数代码:
function ArrivedOk (setJobStart, setArrived){ console.log("OK"); setJobStart(false); setArrived(true); }
方案2:简化逻辑,避免层层传参
直接把 ArrivedOk 定义在 App 组件内部,就可以直接调用内部的状态更新函数,只需要把函数本身传给子组件即可:
function App(){ const [arrived, setArrived ] = useState(false); const [startJob, setJobStart ] = useState(false); // 直接在App内部定义方法,可直接调用内部的setter const ArrivedOk = () => { console.log("OK"); setJobStart(false); setArrived(true); } return( <ActionButtons arrived={arrived} ArrivedOk={ArrivedOk} /> ) } // 子组件直接接收并调用传进来的方法即可 function ActionButtons ({arrived, ArrivedOk, dialer, directions}) { return( <Button title="Arrived" disabled={arrived} onPress={ArrivedOk} buttonStyle={{ backgroundColor: '#0b77b0' }} /> )}
内容的提问来源于stack exchange,提问作者Ryan Fonseka
相关产品推荐
相关产品推荐

