reactjs - 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
.
解决方案
推荐阅读
- scala - Akka Source 不是流数据?
- python - ImportError:没有名为“torchvision.datasets.mnist”的模块
- java - 在 android 应用程序启动之前,进程被终止
- c - 冒泡排序未在 c 中正确排序数组
- mongodb - 在 MongoDB 中链接不相关的集合
- ios - IBDesignable 类似乎无法正常工作
- c# - 使用 LINQ 从 SQL 数据库表中筛选元素
- xamarin - 无法解析引用 Plugin.Permissions
- mysql - 使用mysql拆分值并将分隔值放入两个不同的列
- javascript - 有没有办法在对象中应用条件?