react redux

发布时间:2025-05-13 04:17

React前端开发:FreeCodeCamp的React课程很受欢迎 #生活技巧# #工作学习技巧# #编程学习资源#

2, 第二步骤,我们来看下我们的界面

import React, { Component } from 'react'

import { connect } from 'react-redux';

class ReduxSagaHa extends Component {

constructor(props) {

super(props);

}

render() {

const { count, add } = this.props;

return (

<div>

<p>hello action {count}</p>

<button onClick={() => { this.go() }}>button</button>

</div>

)

}

go() {

this.props.add();

}

}

export default connect(state => ({ count: state.count }),

{

add: () => ({ type: 'add' })

}

)(ReduxSagaHa);

以上没啥,就是用connect 函数连接一下redux

import { createStore, applyMiddleware } from "redux";

import { combineReducers } from "redux"

import mySaga from './sagas'

import logger from "redux-logger"

import createSagaMiddleware from 'redux-saga'

const sagaMiddleware = createSagaMiddleware()

function UseReducer(state = { isLogin: false }, action) {

const type = action.type;

switch (type) {

case "login":

let newState = {

...state,

isLogin: true

}

return newState;

case "logout":

let newS = {

...state,

isLogin: false

}

return newS;

default:

return state;

}

}

function nameReducer(state = { "name": "action" }, action) {

const type = action.type;

switch (type) {

case "init":

let newState = {

...state,

name: "tiantian"

}

return newState;

default:

return state;

}

}

function CountReducer(state = 10, action) {

const type = action.type;

switch (type) {

case "add":

return state;

case "minus":

state--;

return state;

case "asyncAdd":

console.log(action);

state++;

return state;

case "setValue":

state += action.value;

return state;

default:

return state;

}

}

const store = createStore(combineReducers({

count: CountReducer,

name: nameReducer,

user: UseReducer

}), applyMiddleware(logger, sagaMiddleware));

sagaMiddleware.run(mySaga)

export default store;

sagas.js

import { call, put, takeEvery } from 'redux-saga/effects'

function asyncAdd(arg) {

return new Promise((resolve, reject) => {

setTimeout(() => {

resolve(arg + 10);

}, 1000);

});

}

function* addCount(action) {

try {

const value = yield call(asyncAdd, 0);

console.log("value=" + value);

yield put({ type: "setValue", value });

} catch (e) {

yield put({ type: "USER_FETCH_FAILED", message: e.message });

}

}

function* mySaga() {

yield takeEvery("add", addCount);

}

export default mySaga;

saga的原理非常简单,就是监听action 请求,一旦发现,就去执行我们的生成器函数

saga 配置

逻辑我给顺一下,毕竟是线性的

这个时候已经发送 请求了 dispatch({type:'add'})

总之异步的操作都被抽取出来了,很是舒服,爱咋写咋写

行,初步就这些,我们回头继续, dva umi 都要搞定!

网址:react redux https://www.yuejiaxmz.com/news/view/960662

相关内容

使用Redux Toolkit打造任务清单应用实战指南
React任务跟踪器:优化日常生活管理
轻松管理日常任务:React实现个性化的待办事项清单
掌握React,轻松管理日程:高效工作生活新技巧大揭秘
揭秘React助力下的数字游民生活:如何远程工作,自由翱翔?
推荐开源项目:Groceries
推荐一款高效能个人事务管理神器:Tomato Work
【React】React 生命周期完全指南
React Navigation 中文网
【react全家桶学习】react的 (新/旧) 生命周期(重点)

随便看看