React中componentDidMount多次触发,如何确保API仅调用一次?
解决componentDidMount中API多次调用的问题
可能的原因及对应解决方法
React.StrictMode 导致的开发环境双重调用
开发模式下,React.StrictMode会刻意重复调用componentDidMount、componentWillUnmount等生命周期方法,用来检测潜在的副作用问题,生产环境不会出现这个情况。如果是这个原因,要么在开发阶段忽略该现象,要么移除根组件外包裹的<StrictMode>标签。组件被多次挂载/卸载
检查父组件是否存在频繁重新渲染的情况,导致Listings组件被反复卸载后重新挂载。可以通过添加卸载钩子确认:componentWillUnmount() { console.log('Listings组件已卸载'); }如果确认是重复挂载,可通过以下方式优化:
- 用
React.memo包裹组件,避免父组件无关状态变化导致的重新渲染:export default React.memo(Listings); - 确保父组件传递给
Listings的key值稳定,避免因key变化触发组件重新创建。
- 用
添加调用标志位确保只执行一次
在组件实例中添加标志位,记录API是否已调用,避免重复执行:export default class Listings extends Component{ state = { listings: null } // 标记API是否已调用 apiCalled = false; componentDidMount() { this.getAllCryptoListings(); } getAllCryptoListings() { if (this.apiCalled) return; this.apiCalled = true; axios.get('http://localhost:8000/') .then( (res) => { console.log(res.data.data); this.setState({listings: res.data.data}) }) .catch( (error) => { console.log(error); // 请求失败时可重置标志位允许重试,根据需求选择 // this.apiCalled = false; }) } }
顺带修正你的代码问题
原代码中finally里直接访问response.data.data存在风险:如果请求失败,response仍为null,会触发Cannot read properties of null错误。建议把setState移到then中,失败时单独处理,避免报错。
内容的提问来源于stack exchange,提问作者WaqasRaza
相关产品推荐
相关产品推荐

