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

首次使用Redux-React无法展示API响应数据,请求技术帮助

问题解决

1. 修复useState更新的错误用法

你代码里的setArticle(articles, res.data)是错误的——useState的更新函数仅接受单个参数(新的状态值)。如果要把接口返回的res.data设置为新的文章数组,直接传入res.data即可:

const getUserArticle =() =>{
    const id = user._id
    dispatch(fetchUserArticle(id))
        .unwrap()
        .then((res) =>{
            // 正确设置状态
            setArticle(res.data)
            // 在这里打印才能拿到更新后的数据
            console.log(res.data)
        })
    // 这里的console.log会先于异步请求执行,打印的始终是初始空数组
}

另外,你放在then外的console.log(articles)会先执行,因为dispatch是异步操作,所以打印的永远是初始的空数组。如果要查看更新后的状态,要么把console.log移到then内部,要么用useEffect监听状态变化:

useEffect(() => {
    console.log('更新后的articles:', articles)
}, [articles])

2. 更符合Redux规范的写法

既然用了Redux的createAsyncThunk,建议直接把接口数据存在Redux Store中,而非组件内的useState,这样数据可跨组件共享,也更贴合Redux的设计思路:

第一步:在Slice中添加extraReducers处理异步结果

// 你的slice文件
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'

export const fetchUserArticle = createAsyncThunk(
    'article/get-article-user',
    async(id, thunkAPI)=>{
        try{
            const response = await dataService.getUserArticles(id)
            thunkAPI.dispatch(setMessage(response.msg))
            return response.data // 直接返回需要存储的核心数据
        }
        catch(err){
            const message = (err.message && err.response && err.response.message) || err.response || err.toString()
            thunkAPI.dispatch(setMessage(message))
            return thunkAPI.rejectWithValue(message)
        }
    }
)

const articleSlice = createSlice({
    name: 'article',
    initialState: {
        userArticles: [],
        loading: false,
        error: null
    },
    reducers: {
        // 你的其他reducer逻辑
    },
    extraReducers: (builder) => {
        builder
            // 请求中状态
            .addCase(fetchUserArticle.pending, (state) => {
                state.loading = true
                state.error = null
            })
            // 请求成功,更新store数据
            .addCase(fetchUserArticle.fulfilled, (state, action) => {
                state.loading = false
                state.userArticles = action.payload
            })
            // 请求失败,记录错误信息
            .addCase(fetchUserArticle.rejected, (state, action) => {
                state.loading = false
                state.error = action.payload
            })
    }
})

export default articleSlice.reducer

第二步:组件中用useSelector获取Store数据

// index.js文件
import { useDispatch, useSelector } from 'react-redux'

const UserAticles = (props)=>{
    const dispatch = useDispatch()
    // 从Redux Store中直接获取数据
    const { userArticles, loading, error } = useSelector(state => state.article)

    useEffect(()=>{
        getUserArticle()
    },[])

    const getUserArticle =() =>{
        const id = user._id
        dispatch(fetchUserArticle(id))
    }

    // 渲染逻辑
    if (loading) return <div>加载中...</div>
    if (error) return <div>出错了:{error}</div>

    return (
        <div>
            {userArticles.map(article => (
                <div key={article._id}>{article.title}</div>
            ))}
        </div>
    )
}

这样就无需组件内的useState,直接从Redux Store获取数据,状态管理更清晰可控。

内容的提问来源于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.02 18:20:33