如何在抽离到工具文件的React函数中设置组件状态?
报错根因
原函数内嵌在类组件内部时,属于组件实例方法的一部分,运行时this会自动绑定当前组件实例,因此可以直接调用this.setState。抽离为独立工具函数后,函数不再绑定任何组件上下文,调用时this默认指向undefined(严格模式下),因此触发读取setState属性失败的报错。
适配调整方案
核心思路是把原本隐式绑定的组件上下文,通过函数入参显式传入,既保留原有的状态更新逻辑,又让工具函数可以在多组件间复用。
方案1:直接传入组件实例
调整工具函数代码,新增组件实例入参,替换原函数内的隐式this:import axios from 'axios'; export const getGalaxyName = async (componentInstance, id) => { try { const { data: response } = await axios.get(`/api/scienceClass/galaxy/${id}`) // 用传入的组件实例调用setState,和原有逻辑完全一致 componentInstance.setState({ galaxyName: response.name }); } catch (error) { console.log(error); } }组件内调用时,把当前类组件的实例
this作为入参传入:import { getGalaxyName } from './ScienceClassUtils'; componentDidMount() { getGalaxyName(this, slide.z_GalaxyId); }注意:原代码在render生命周期内直接调用请求函数的写法不建议保留,render会随状态更新反复执行,容易造成请求重复发送、状态更新触发无限循环的问题,推荐把调用逻辑放到组件生命周期钩子、用户事件回调中执行。
方案2:低耦合优化,只传入setState方法
如果不想把整个组件实例透传给工具文件,可以单独将绑定好上下文的setState方法作为入参传入,减少工具函数和组件的耦合:
调整后的工具函数:import axios from 'axios'; export const getGalaxyName = async (setStateFn, id) => { try { const { data: response } = await axios.get(`/api/scienceClass/galaxy/${id}`) setStateFn({ galaxyName: response.name }); } catch (error) { console.log(error); } }组件内调用时,传入绑定了当前组件上下文的setState:
import { getGalaxyName } from './ScienceClassUtils'; componentDidMount() { getGalaxyName(this.setState.bind(this), slide.z_GalaxyId); }
内容的提问来源于stack exchange,提问作者SkyeBoniwell
相关产品推荐
相关产品推荐

