React项目中传入setState后服务方法state参数仍为undefined问题
问题原因分析
核心问题:函数名拼写不一致
你在API服务中导出的函数名为 getProductCustoumer(注意拼写:Custoumer,中间多了一个字母u),但在组件的useEffect中调用的是 getProductCustomer(正确拼写:Customer)。
这种拼写错误会导致:
- 你实际调用的并不是你定义的那个带有
state参数的函数(如果项目中没有其他同名的getProductCustomer函数,控制台应该还会报“函数未定义”的错误) - 即使存在其他同名函数,也会因为参数不匹配,导致当前你写的这个
getProductCustoumer函数根本没被执行,自然其中的state参数会是undefined。
其他优化点(非直接原因,但建议修正)
- 避免
await和.then混用:API服务中的代码可以简化,无需在await后再用.then,同时可以用可选链避免state未传入时报错:
export const getProductCustomer = async (customerid, state) => { const result = await api.get(`ProductCustomer?customerid=${customerid}`); const data = result.data; state?.(data); return data; };
- 组件中无需重复调用
setData:因为服务函数已经会调用state(data),组件里拿到返回值后再调用setData(response)属于重复操作,直接去掉即可。
内容的提问来源于stack exchange,提问作者Kuo
相关产品推荐
相关产品推荐

