首页 > 解决方案 > Redux-saga 不更新存储状态

问题描述

我正在使用 redux-saga 来获取一个端点,并希望在第一页加载时使用useEffect(). 但我的没有得到任何东西。屏幕是空白的,reduxDevTools 也没有显示任何内容。我不明白我错过了什么。

我的saga

export function* watcherSaga() {
    yield takeLatest("FETCH_TOP_NEWS_REQUEST", workerSaga);}

function fetchTopNews() {
    return axios({
        method: 'get',
        url: 'https://newsapi.org/v2/top-headlines?country=us&apiKey=API_KEY'
    });}

function* workerSaga() {
    try{
        const response = yield call(fetchTopNews);
        const news = response.data.articles;

        yield put({ type: "FETCH_TOP_NEWS_SUCCESS", news });
    }
    
    catch (error) {
        yield put({ type: "FETCH_TOP_NEWS_ERROR", error });
    }
}

我定义了 3 个动作

const initialState = {
    fetching: false,
    error: null,
    news: []
};

const NewsReducer = (state=initialState, action) => {
    switch(action.type){
        case types.fetchTopNewsRequest:
            return { ...state, fetching: true, error: null };
        case types.fetchTopNewsSuccess:
            return { ...state, fetching: false, news: action.news[0] };
        case types.fetchTopNewsError:
            return { ...state, fetching: false, news: null, error: action.error };
        default:
            return state;
    }
}

export default NewsReducer;

最后我的组件,我在这里导入了fetchTopNewsRequest()动作:

const TopHeadline = (props) => {
    const { news, getTopNews } = props;

    useEffect(() => {
        getTopNews();
    }, [getTopNews]);

    return (
        <div className="newsItem">
            <h1>Title: {news.title}</h1>
        </div>
    );}

const mapStateToProps= (state) => {
    return {
        news: state.news,
    };
};

const mapDispatchToProps = (dispatch) => {
    return {
        getTopNews: () => dispatch( fetchTopNewsRequest() )
    };
};

export default connect(mapStateToProps, mapDispatchToProps)(TopHeadline);

我试图只获取articles.title.

DevTools 显示它已成功获取数据: 开发工具操作选项卡

购买我的状态没有更新:devtools-状态-不更新

标签: reactjsreduxreact-reduxaxiosredux-saga

解决方案


推荐阅读