ade*_*del -1 javascript reactjs redux redux-thunk react-redux
您好,我正在尝试redux从给定的数据中获取存储的初始数据api!
这是我使用的第一种方法store.dispatch:
import { createStore, applyMiddleware, compose } from "redux";
import thunk from "redux-thunk";
import reducer from "./reducer";
import { fetchNews } from "./actions";
const store = createStore(
reducer,
compose(
applyMiddleware(thunk),
window.__REDUX_DEVTOOLS_EXTENSION__ &&
window.__REDUX_DEVTOOLS_EXTENSION__()
)
);
store.dispatch(fetchNews());
export default store;
Run Code Online (Sandbox Code Playgroud)
第二种方法是从组件生命周期方法分派操作,如下所示:
import React from "react";
import axios from "axios";
import InfiniteScroll from "react-infinite-scroller";
import { useSelector, useDispatch } from "react-redux";
import New from "./New";
import { fetchNews } from "../store/actions";
const Main = () => {
const news = useSelector(state => state.news);
const dispatch = useDispatch();
React.useEffect(() => {
dispatch(fetchNews());
}, [dispatch]);
return (
<>
{news.length > 0 ? (
news.map(data => (
<New key={data.id} subTitle={data.created_at}>
{data.title}
</New>
))
) : (
<p>News not found</p>
)}
</>
);
};
Run Code Online (Sandbox Code Playgroud)
好的,两种方法都可以,但是我真的很想知道什么是更好的方法,或者还有其他更好的方法!谢谢!
| 归档时间: |
|
| 查看次数: |
54 次 |
| 最近记录: |