Redux:Redux Flows

本文详细介绍了Redux的基本安装与配置,包括如何创建初始状态、Reducer、Store和订阅更新。同时,深入探讨了Redux与React的集成,展示了如何通过Provider组件传递store,并在组件中使用connect映射状态和dispatch。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

安装redux

npm install --save redux

建立初始state

const redux = require('redux');
const createStore = redux.createStore;

const initialState={
    counter:0
}

Reducer(当前state,action)

每次改变都需要用深拷贝;
不能在传入的state中进行原地改变;

//Reducer
const rootReducer = (state=initialState, action) =>{ // 传入当前状态和操作
    if(action.type==='INC_COUNTER'){
        //不能改变任何data
        return {
            ...state,
            counter: state.counter+1   //不能使用state.counter++, 不能mutate
        };
    };
    if(action.type==='ADD_COUNTER'){
        //不能改变任何data
        return {
            ...state,
            counter: state.counter+action.value   //不能使用state.counter++, 不能mutate
        };
    };

    return state;       //返回当前state

};    

Store

将state存储在store中;
用store.getstate()得到存储的state;

//Store
const store = createStore(rootReducer);
console.log(store.getState());

Subscriptions

store.subscribe() 放入一个funciton,每当store内容变化时(dispatch),执行function;

//Subscriptions               //在storecreate后设置,后面的dispatch会被监控
store.subscribe(()=>{
    console.log('[subscription]',store.getState());
});

Dispatching Action

store.dispatch(),参数为一个obj,必有一个type(在reducer中传入的(state,action)中条件判断);

//Dispatching Action
store.dispatch({type: 'INC_COUNTER'});
store.dispatch({type: 'ADD_COUNTER', value:10});
console.log(store.getState());   

//store内容会随着dispatch改变
//reducer控制dispatch传入的action
//reducer接收store当前的state,与dispatch传入的action
//返回action后的state,放入store中

将redux用于react(BASIC)

npm install --save react-redux

Reducer

reducer为一个函数;
传入initialState用于store的create;
设置action,条件判断type等参数用于改变store;

const initialState = {
    counter:0
}

const reducer = (state=initialState, action) =>{
    if(action.type==='INCREMENT')
    {
        return {                      //return一个obj,不在原地修改
            counter:state.counter+1
        };
    }
    else if(action.type==='DECREMENT'){
        return{
            counter:state.counter-1
        };
    }else if(action.type==='ADD'){
        return {
            counter:state.counter+5
        };
    }else if(action.type==='SUB'){
        return {
            counter:state.counter-5
        };
    }

    return state;
}

export default reducer;

Store=createStore(reducer)

在index.js中用Provider包住app,传入建立的store

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

import {createStore} from 'redux';
import reducer from './store/reducer'; 
import {Provider} from 'react-redux';   //用于将store放入react
//create store
const store = createStore(reducer);

//传入store到app
ReactDOM.render(
<Provider store={store}> 
    <App />
</Provider>   , document.getElementById('root'));
registerServiceWorker();

将store和dispatch传入需要的component中

import React, { Component } from 'react';

import CounterControl from '../../components/CounterControl/CounterControl';
import CounterOutput from '../../components/CounterOutput/CounterOutput';


import {connect} from 'react-redux';
class Counter extends Component {
    render () {
        return (
            <div>
                <CounterOutput value={this.props.ctr} />
                <CounterControl label="Increment" clicked={this.props.onIncrementCounter} />
                <CounterControl label="Decrement" clicked={this.props.onDecrementCounter}  />
                <CounterControl label="Add 5" clicked={this.props.onAdd}  />
                <CounterControl label="Subtract 5" clicked={this.props.onSub}  />
            </div>
        );
    }
}
//在class后定义,将reducer中的state选部分作为props传入上面的component中
const mapStateToProps = state=>{            //从reducer中引入state.counter,作为ctr在此使用
    return {
        ctr:state.counter
    };
}

//传入需要dispatch的action
const mapDispatchToProps = dispatch=>{
    return {
        onIncrementCounter: ()=> dispatch({type:'INCREMENT'}),
        //设置Decrement
        onDecrementCounter: ()=> dispatch({type:'DECREMENT'}),
        //设置Add
        onAdd:()=>dispatch({type:'ADD'}),
        onSub:()=>dispatch({type:"SUB"})
    };
}


//传入需要的stateprops和dispatch props
export default connect(mapStateToProps,mapDispatchToProps)(Counter);
//connect() 返回一个hoc funtion

1.设置需要传入的state,用一个变量,返回一个obj

const mapStateToProps = state=>{            //从reducer中引入state.counter,作为ctr在此使用
    return {
        ctr:state.counter
    };
}

2.设置需要用到的dispath,设置一个const,传入一个obj

const mapDispatchToProps = dispatch=>{
    return {
        onIncrementCounter: ()=> dispatch({type:'INCREMENT'}),
        //设置Decrement
        onDecrementCounter: ()=> dispatch({type:'DECREMENT'}),
        //设置Add
        onAdd:()=>dispatch({type:'ADD'}),
        onSub:()=>dispatch({type:"SUB"})
    };
}

3.将上述两个const传入connect方法,即可在当前的counter component中的props调用传入的state和dispatch了;

export default connect(mapStateToProps,mapDispatchToProps)(Counter);

passing addtional data

在设置 dispath->{
return{
name:()=>dispatch({})
}
}
时,除了传入type,再传入所需的data;

//传入需要dispatch的action
const mapDispatchToProps = dispatch=>{
    return {
        onIncrementCounter: ()=> dispatch({type:'INCREMENT'}),
        //设置Decrement
        onDecrementCounter: ()=> dispatch({type:'DECREMENT'}),
        //设置Add
        onAdd:()=>dispatch({type:'ADD',val:5}),
        onSub:()=>dispatch({type:"SUB",val:5})
    };
}

后在reducer中对传入的action.data进行设置;

return {
            counter:state.counter+action.val
        };
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值