react_redux_saga使用

创建项目

npx create-react-app my-app

创建 redux目录

目录下分别创建目录reducers、actions、saga
在这里插入图片描述

安装

yarn add redux --save
yarn add react-redux
yarn add redux-thunk
yarn add redux-saga

actions

src\redux\actions

import { USER } from "./index";

// export const FETCH_USER_LIST = USER + "FETCH_USER_LIST";

export const FETCH_USER_LIST = () => {
    return {
        type: USER + "FETCH_USER_LIST",
    };
};


reducers

src\redux\reducers\index.js

import { combineReducers } from "redux";
import userReducers from "./userReducers";
const rootReducer = combineReducers({ userReducers });
export default rootReducer;

src\redux\reducers\userReducers.js

import { USER } from "./index";

export const USER_overrideStateProps = USER + "overrideStateProps";
export const USER_updateStateProps = USER + "updateStateProps";

export const FETCH_USER_LIST = () => {
    return {
        type: USER + "FETCH_USER_LIST",
    };
};

saga

src\redux\saga\index.js

import { call, put, take, all, fork } from "redux-saga/effects";

import userSaga from "./userSaga";

export default function* rootSaga() {
    yield all([fork(userSaga)]);
}

``
src\redux\saga\userSaga.js

```javascript
import { call, put, take, all, fork } from "redux-saga/effects";
import * as actions from "../actions/userActions";
import { delay } from "redux-saga";

function* fetchUserList() {
    console.log("请求用户");
    yield call(delay, 1000); // 需要执行异步的时候,直接调用 call
    yield put({
        type: "ADD",
    });
}

function* fetchUserListAsync() {
   console.log("监听请求用户action");
    // while (true) {
    //     const { payload } = yield take(actions.USER_LIST_ASYNC);
    //     yield fork(getUserList, payload);
    //     console.log("payload", payload);
    // }
    yield takeEvery("USER/USER_LIST_ASYNC", function* ({ payload }) {
        console.log("payload", payload);
        yield fork(getUserList, payload);
    });
}

export default function* () {
    yield all([fork(fetchUserListAsync)]);
}

store

import { createStore, applyMiddleware } from "redux";
import reducer from "./reducers";
import rootSaga from "./saga";

import createSagaMiddleware from "redux-saga";
const sagaMiddleware = createSagaMiddleware();
const store = createStore(reducer, applyMiddleware(sagaMiddleware)); //创建仓库
sagaMiddleware.run(rootSaga);

export default store; //暴露store

入口文件

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { Provider } from "react-redux";
import store from "./redux/store";
ReactDOM.render(
    <React.StrictMode>
        <Provider store={store}>
            <App />
        </Provider>
    </React.StrictMode>,
    document.getElementById("root")
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

使用方式connect

import { connect, useDispatch } from "react-redux";
import "./App.css";

function App(props) {
    console.log(11, props);
    return (
        <div className="App">
            <div>Learn React</div>
        </div>
    );
}
const mapStateToProps = (state) => {
    return {
        userReducers: state.userReducers,
    };
};
const mapDispatchToProps = (dispatch) => {
    return {};
};
export default connect(mapStateToProps, mapDispatchToProps)(App);

使用方式hooks

import { useDispatch, useSelector } from "react-redux";
import "./App.css";
import store from "./redux/store";

function App(props) {
    const dispatch = useDispatch();
    const user = useSelector((store) => store.userReducers);
    console.log(11, props);
    console.log("user", user);
    const handleMin = () => {
        console.log(99);
        dispatch({
            type: "USER/overrideStateProps",
            payload: {
                number: 3,
            },
        });
    };
    const handleChangeUser = () => {
        dispatch({
            type: "USER/updateStateProps",
            payload: {
                name: "userInfo",
                value: {
                    name: "修改对象",
                    name2: "修改对象33",
                },
            },
        });
    };
    const handleChangeUserAsync = () => {
        dispatch({
            type: "USER/FETCH_USER_LIST",
        });
    };

    return (
        <div className="App">
            <div>Learn React</div>
            <button onClick={handleMin}>-</button>
            <button onClick={handleChangeUser}>同步修改用户</button>
            <button onClick={handleChangeUserAsync}>异步修改用户</button>
        </div>
    );
}

export default App;


saga理解

saga文档
简单理解 ‘redux-saga/effects’ 中的几个关键字:fork,call, put,takeEvery,takeLatest,all

fork :创建一个新的进程或者线程,并发发送请求。
call:发送 api 请求

put:发送对应的 dispatch,触发对应的 action

takeEvery:监听对应的 action;
每一次 dispatch 都会触发;例如:点击一个新增的按钮,2s 后触发新增动作,在2s内不断点击按钮,这时候,每一次点击,都是有效的。
yield takeEvery(‘FETCH_USER’, fetch_user);

takeLatest:监听对应的 action;
只会触发最后一次 dispatch;例如:点击一个新增的按钮,2s 后触发新增动作,在2s内不断点击按钮,这时候,只有最后一次点击是有效的。
yield takeLatest(‘FETCH_USER’, fetch_user);

all:跟 fork 一样,同时并发多个 action,没有顺序。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
前端开发中的React Redux全家桶是一套常用的技术栈,用于构建复杂的Web应用程序。React是一个由Facebook开发的JavaScript库,用于构建用户界面。它通过将应用程序拆分成可重用的组件,使开发人员能够更轻松地开发、测试和维护Web应用程序。 Redux是一个用于管理应用程序状态的库。它采用了一种称为单一状态树的模式,将整个应用程序的状态存储在一个对象中,并使用纯粹的函数来修改状态。Redux的核心概念包括:store、reducer和action。Store是应用程序的状态容器,reducer是一个纯函数,用于根据action来修改状态,而action代表用户触发的操作。 React Redux是将ReactRedux结合在一起使用的库。通过使用React Redux,我们可以将Redux的状态管理功能集成到React组件中。React Redux提供了一种称为容器组件的机制,它负责从Redux store中提取数据,并将其作为props传递给展示组件。这种分离开发的模式使得代码更加模块化和易于维护。 React Redux全家桶还包括一些其他的辅助库,如React Router用于跟踪和管理应用程序的URL路径,以及Redux Thunk或Redux Saga用于处理异步操作。这些库的整合和使用能够帮助开发人员构建可扩展、高效和易于维护的前端应用程序。 总之,前端开发中的React Redux全家桶提供了一套完善的工具和库,帮助开发人员构建复杂的Web应用程序。它能够将状态管理和用户界面开发结合在一起,并提供了一种模块化和分离开发的解决方案。通过学习和使用React Redux全家桶,开发人员可以提高开发效率,并构建出更好的用户体验。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值