Redux-Saga不更新商店状态

时间:2020-08-26 17:55:43

标签: reactjs redux react-redux axios 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-action-tab

购买我的状态未更新:devtools-states-not-updating

0 个答案:

没有答案