赞
踩
(1)定义:用于存储整个应用的 state 数据的唯一容器
(2)使用:
① 新建文件夹 store,再添加 index.js,, 内容如下:
import { legacy_createStore as createStore, combineReducers} from 'redux'
import countReducer from "./reducer/countReducer"
import listReducer from "./reducer/listReducer"
import objReducer from './reducer/objReducer';
export default createStore(combineReducers({
countReducer,
listReducer,
objReducer
}));
createStore函数接受纯函数作为参数,返回新生成的 Store 对象;
combineReducers 将多个 reducer (处理不同数据时,需要抽离多个reducer)合并成为一个;
② 在 src/index.js 中引入 src/store/index.js
react-redux 提供Provider组件,让所有子组件都可以拿到state
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { BrowserRouter } from "react-router-dom";
import { Provider } from 'react-redux/es/exports';
import store from './store';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
);
// src/store/action.js
function add() {
return {
type: 'ADD',
}
}
function minus() {
return {
type: 'MINUS'
}
}
export default {add, minus};
// src/store/reducer/countReducer .js
import types from "../constant";
export default function countReducer (state = 0, action) {
switch (action.type) {
case types.ADD:
return state + 1;
case types.MINUS:
return state - 1;
default:
return state;
}
}
// S 是实现组件,默认导出容器组件 import React from "react"; import {connect} from "react-redux"; import types from "../../../store/constant"; class S extends React.Component { render () { return ( <div> <p>store-count: {this.props.count}</p> <button onClick={() => {this.props.add()}}>+</button> <button onClick={() => {this.props.minus()}}>-</button> <ul> {this.props.list.map((v, i) => { return (<li key={i}>{v}</li>) })} </ul> </div> ) } } export default connect( state => ({ count: state.countReducer, list: state.listReducer }), dispatch => ({ add: () => { dispatch({type: types.ADD_LIST}) }, minus: () => { dispatch({type: types.MINUS_LIST}) }, }) )(S);
npm install redux-thunk
在 Redux 应用中引入 redux-thunk 中间件,并将其添加到 Redux Store 的中间件链中。
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
const store = createStore(
rootReducer,
applyMiddleware(thunk)
);
在组件中使用
import { useDispatch } from "react-redux"; import { Button } from 'antd'; import userApi from "../../api/user"; function Asy () { let dispatch = useDispatch(); const actionFn = (type, response) => { return {type, payload}; } const fetchPosts = postTitle => (dispatch, getState) => { dispatch(actionFn ("FETCH_DATA_PENDING")); return userApi.userList({ "username": "", "insDateStartStr": "2023-01-01 00:00", "insDateEndStr": "2023-12-31 23:59", "pageSize": 10, "pageNum": 1 }).then(res => { let data = res.data || {}; dispatch(actionFn("FETCH_DATA_FULFILLED", data)) }).catch(err => { dispatch(actionFn("FETCH_DATA_REJECTED", err)) }) }; return ( <div> <Button type="primary" onClick={handleClick}>query</Button> </div> ) } export default Asy;
5.2 redux-promise
允许你在 Redux 中处理异步操作,并且简化了异步操作的状态管理过程。
使用 redux-promise 需要进行以下步骤:
安装 redux-promise 包:
npm install redux-promise
在 Redux 应用中引入 redux-promise 中间件,并将其添加到 Redux Store 的中间件链中。
import { createStore, applyMiddleware } from 'redux';
import promiseMiddleware from 'redux-promise';
import rootReducer from './reducers';
const store = createStore(
rootReducer,
applyMiddleware(promiseMiddleware)
);
定义 Action Creator,用于创建带有异步操作的 Action。
import axios from 'axios';
export const fetchData = () => {
return {
type: 'FETCH_DATA',
payload: axios.get('/api/data') // 异步操作,返回一个 Promise
};
};
在 Reducer 中处理异步操作的 Action。
const initialState = { data: null, loading: false, error: null }; const reducer = (state = initialState, action) => { switch (action.type) { case 'FETCH_DATA_PENDING': return { ...state, loading: true }; case 'FETCH_DATA_FULFILLED': return { ...state, loading: false, data: action.payload.data }; case 'FETCH_DATA_REJECTED': return { ...state, loading: false, error: action.payload }; default: return state; } };
参照 Redux 入门教程(二):中间件与异步操作 - 阮一峰 等node接口写好了,对接后补充此模块
import React, { useReducer } from 'react'; // 定义 reducer 函数 const reducer = (state, action) => { switch (action.type) { case 'INCREMENT': return { count: state.count + 1 }; case 'DECREMENT': return { count: state.count - 1 }; default: return state; } }; const Counter = () => { // 使用 useReducer 创建状态和状态更新函数 const [state, dispatch] = useReducer(reducer, { count: 0 }); return ( <div> <p>Count: {state.count}</p> <button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button> <button onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement</button> </div> ); }; export default Counter;
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。