【redux】redux-thunk 使用案例
redux-thunk
是一个用于处理 Redux 异步操作的中间件。它允许我们在 Redux action 中执行异步操作,比如网络请求。下面是一个使用 redux-thunk
的案例,展示如何在 React 应用中进行异步数据获取并将数据存储在 Redux store 中。
1. 安装依赖
首先安装 redux、react-redux 和 redux-thunk:
npm install redux react-redux redux-thunk
2. 配置 Redux Store
配置 Redux store 并应用 redux-thunk 中间件:
// src/store.js
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
const store = createStore(rootReducer, applyMiddleware(thunk));
export default store;
3. 创建 Actions 和 Action Creators
创建常规的 actions 和一个用于处理异步操作的 thunk action creator:
// src/actions/postActions.js
import axios from 'axios';
// Action types
export const FETCH_POSTS_REQUEST = 'FETCH_POSTS_REQUEST';
export const FETCH_POSTS_SUCCESS = 'FETCH_POSTS_SUCCESS';
export const FETCH_POSTS_FAILURE = 'FETCH_POSTS_FAILURE';
// Action creators
const fetchPostsRequest = () => {
return {
type: FETCH_POSTS_REQUEST,
};
};
const fetchPostsSuccess = (posts) => {
return {
type: FETCH_POSTS_SUCCESS,
payload: posts,
};
};
const fetchPostsFailure = (error) => {
return {
type: FETCH_POSTS_FAILURE,
payload: error,
};
};
// Thunk action creator
export const fetchPosts = () => {
return (dispatch) => {
dispatch(fetchPostsRequest());
axios
.get('https://jsonplaceholder.typicode.com/posts')
.then((response) => {
const posts = response.data;
dispatch(fetchPostsSuccess(posts));
})
.catch((error) => {
dispatch(fetchPostsFailure(error.message));
});
};
};
4. 创建 Reducer
创建一个用于处理 posts 状态的 reducer:
// src/reducers/postsReducer.js
import {
FETCH_POSTS_REQUEST,
FETCH_POSTS_SUCCESS,
FETCH_POSTS_FAILURE,
} from '../actions/postActions';
const initialState = {
loading: false,
posts: [],
error: '',
};
const postsReducer = (state = initialState, action) => {
switch (action.type) {
case FETCH_POSTS_REQUEST:
return {
...state,
loading: true,
};
case FETCH_POSTS_SUCCESS:
return {
loading: false,
posts: action.payload,
error: '',
};
case FETCH_POSTS_FAILURE:
return {
loading: false,
posts: [],
error: action.payload,
};
default:
return state;
}
};
export default postsReducer;
5. 组合 Reducers
如果你有多个 reducers,可以使用 combineReducers 进行组合:
// src/reducers/index.js
import { combineReducers } from 'redux';
import postsReducer from './postsReducer';
const rootReducer = combineReducers({
posts: postsReducer,
});
export default rootReducer;
6. 创建 React 组件并连接 Redux
使用 React-Redux 的 connect 方法来连接 Redux store,并在组件中触发异步请求。
// src/components/PostsList.js
import React, { useEffect } from 'react';
import { connect } from 'react-redux';
import { fetchPosts } from '../actions/postActions';
const PostsList = ({ postsData, fetchPosts }) => {
useEffect(() => {
fetchPosts();
}, [fetchPosts]);
if (postsData.loading) {
return <p>Loading...</p>;
}
if (postsData.error) {
return <p>Error: {error}</p>;
}
return (
<div>
<h2>Posts List</h2>
<ul>
{postsData.posts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
};
const mapStateToProps = (state) => {
return {
postsData: state.posts,
};
};
const mapDispatchToProps = (dispatch) => {
return {
fetchPosts: () => dispatch(fetchPosts()),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(PostsList);
或者,使用 React-Redux 的 useDispatch 和 useSelector 钩子来连接 Redux store,并在组件中触发异步请求。(推荐)
// src/components/PostsList.jsx
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { fetchPosts} from '../actions/postActions';
const PostsList= () => {
const dispatch = useDispatch();
const { loading, posts, error } = useSelector((state) => state.data);
useEffect(() => {
dispatch(fetchPosts ());
}, [dispatch]);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error}</p>;
return (
<div>
<h2>Posts List</h2>
<ul>
{postsData.posts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
};
export default PostsList;
7. 连接 Redux Provider
确保你的应用使用 Provider 组件来传递 Redux store:
// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
import PostsList from './components/PostsList';
const App = () => (
<Provider store={store}>
<PostsList />
</Provider>
);
ReactDOM.render(<App />, document.getElementById('root'));
总结
通过使用 redux-thunk
,你可以轻松地处理 Redux 中的异步操作。主要步骤包括:
- 安装和配置中间件:在 Redux store 中应用
redux-thunk
中间件。 - 创建 actions 和 action creators:定义用于异步操作的 thunk action creators。
- 创建 reducer:处理异步操作的状态变化。
- 在 React 组件中使用 Redux:使用
connect
或者hook
方法来连接 Redux store,并触发异步请求。 - 连接 Redux Provider:确保你的应用使用
Provider
组件来传递 Redux store。
通过这些步骤,你可以灵活地在 Redux 中处理 AJAX 请求,简化异步逻辑,提高代码的可读性和维护性。