You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React-Redux异步Get请求重复调用问题求助

React-Redux API请求重复调用问题解决

我正在开发React博客项目,使用React-Redux通过API发送Get请求时,遇到请求函数被持续调用的问题,而非仅执行一次。以下是相关代码及展示重复调用的截图:

重复API调用截图

发起API请求的action文件

export function fetchArticles(){
    return function(dispatch){
        const url  = `${baseUrl}/articles/list`
        return axios.get(url).then(res =>{
        console.log(res.data)
        dispatch( {type:articles.DISPLAY_ARTICLE, payload:res.data.data})
    })
    }
    
}

reducer文件

function displayArticles (state=initialState, action){
    if(action.type===DISPLAY_ARTICLE){
        console.log(state)
        return Object.assign({}, state,{
            articles: state.articles.concat(action.payload)
        })
    }
    console.log(state)
    return state
}


function rootReducer(state=initialState, action){

    switch(action.type){
        case DISPLAY_ARTICLE:
            return displayArticles(state, action)
            break;

组件文件

function mapStateToProp (state){
    return {articles: state.articles}
}
const Index = (props)=>{
  useEffect(()=>{ 
    props.fetchArticles()

  }
  )

export default connect(
    (mapStateToProp),
    {fetchArticles}
)(Index)

问题原因与解决方法

  • 核心问题:组件中的useEffect未设置依赖数组,导致组件每次渲染时都会执行fetchArticles;而fetchArticles触发action更新Redux状态,状态更新又会引发组件重新渲染,形成循环调用。
  • 解决步骤:
    1. 给useEffect添加空依赖数组,确保请求仅在组件挂载时执行一次:
      useEffect(()=>{ 
        props.fetchArticles()
      }, []) // 空依赖数组限定仅挂载阶段执行
      
    2. 优化reducer逻辑(可选):如果不需要累加文章数据,将concat改为直接赋值,避免不必要的状态更新:
      // 在displayArticles函数中修改
      articles: action.payload // 替换原有数据,而非拼接
      

内容的提问来源于stack exchange,提问作者Tosin Ayoola

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 20:01:10