Redux基础使用与入门

React-Redux是Redux的官方React绑定数据的库。它能够使你的React组件从store中读取数据,操作数据并且向store分发actions以更新数据。

初体验

工作流:state状态 -> 到视图展示 -> 通过action操作reducer -> render操作仓库数据
流程:

const reducer = (state, action) => {
return state }

  1. 创建仓库 const store = Redux.createStore(reducer)
  2. 获取数据 store.getState()
  3. 更新数据 store.dispatch({type:,payload})
  4. 监控数据 store.subscribe

步骤1:在src目录下创建仓库store.js文件
步骤2:redux devTool

// 1. 导入redux库(yarn add redux)
// 2. 导入reducers
// 3. 创建仓库store
// 4:下载配置谷歌扩展程序 //https://173app.com/apps/lmhkpmbekcpmknklioeibfkpmmfibljd
// 5:yarn add redux-devtools-extension
// 6:修改store.js
import {createStore} from 'redux'
import {composeWithDevTools} from "redux-devtools-extension"
const initState = {
    data: [
        {id:1, title:'标题1', num:1, price:1.11},
        {id:2, title:'标题2', num:2, price:2.22},
        {id:3, title:'标题3', num:3, price:3.33}
    ],
}
const cartReducer = (state = initState, action) => {
    switch (action.type) {
        case 'CART_INCR':
            tmp.data[action.payload].num += 1
            return tmp
            // break;  
        case 'CART_DECR':
            tmp.data[action.payload].num -= 1
            return tmp
            // break;
        default: 
            break;
    }
    return state
}

export default createStore(cartReducer, composeWithDevTools())

步骤3:在index.js中传递给App.js传递给pages/cart/index.js组件

import React from 'react';
import ReactDOM from 'react-dom';

// 状态
import store from './store';

// 组件
import App from './App';

ReactDOM.render(<App store={store} />, document.getElementById('root')); 

import React, { Component } from ‘react’;

// 组件
import CartIndex from './pages/cart/index'

class App extends Component 
{
  render() {
    return (
      <div>
        <CartIndex store={this.props.store}/>
      </div>
    );
  }
}

export default App;

步骤4:在pages/cart/index.js组件中接受数据

//接受数据
 constructor(props)
    {   
        super(props)

        this.state = {
            carts: props.store.getState().data
        }
    }
    //更新数据
       changeNumFn(option,index)
    {
        // console.log(option, index)

        let type = option === '+' ? 'CART_INCR' : 'CART_DECR'

        this.props.store.dispatch({
            // type: 'CART_INCR/CART_DECR', 
            type, 
            payload: index
        })
    }
    //监听更新数据
     componentDidMount()
    {
        this.props.store.subscribe(() => {
            this.setState({
                carts: this.props.store.getState().carts.data
            })
        })
    }

强化版:react-redux动态监听
修改index.js

import {Provider} from 'react-redux'
<Provider store={store}>
    <App />
</Provider>

组件js文件中修改

import {connect} from 'react-redux'
//操作数据
changeNumFn(option, index)
    {
        if (option === '-')
        {
            // this.props.store.dispatch(decrment(index))
            this.props.del(index)
        } else {
            // this.props.store.dispatch(incrment(index))
            this.props.add(index)
        }
    }
//获取数据
render() {

        // 1. 导入数据
        let {
            carts
        } = this.props
        // 2. 渲染
        return (代码)
    }

const mapStateToProps = state => { // state就是store里面的数据
    return {
        // 键: state.数据
        carts: state.carts.data
    }
}
const mapDispatchToProps= dispatch => {
    return {
        // 参数写不写,根据action需求
        // 键: (index) => dispatch(incrment(index))
        add: index => dispatch(incrment(index)),
        del: index => dispatch(decrment(index))
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(index)

Connect() 连接组件和store,容器属性中使用 两个参数:mapStateToProps和mapDispatchToProps,mapStateToProps抽取数据(mapState),mapDispatchToProps分发actions

redux-thunk中间件(作用:让action中写异步请求)
修改

// import {createStore} from 'redux' 
// combineReducers用来合并数据的
// import {createStore, combineReducers} from 'redux'			
import {createStore, applyMiddleware} from 'redux'  // 改1
import thunk from 'redux-thunk'		                // 改2
import {combineReducers} from 'redux-immutable';					
import {composeWithDevTools} from "redux-devtools-extension"

// export default createStore(cartReducer, composeWithDevTools())
export default createStore(combineReducers({
    carts,
    orders,
}), composeWithDevTools(applyMiddleware(thunk)))    // 改3

使用语法

//引入api中文件
import {seeOrder} from '../../../api/index.js';
export const showStatus = (params)=>{
  // console.log(params)
  return dispatch => {
    seeOrder(params).then(res=>{
      // console.log(res.data)
      if( res.meta.status === 200 ){
        dispatch({                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
          type:'ORDER_SHOW',
          payload:res.data
        })
      }
    })
  }
}  

redux-thunk 它唯一的作用就是让 dispatch 中可以写函数。能够让 store.dispatch()
既能接收函数做为参数,又能接收对象做为参数。

  1. 如果参数是对象的话,这个对象我们一般称为 普通动作对象 (plain object)
  2. 如果参数是函数的话,这个函数我们一般称为 异步动作函数 (async action)

模块化
在store中创建index.js

// 导入模块
import thunk from 'redux-thunk'		               
import {createStore, applyMiddleware} from 'redux' 
import {composeWithDevTools} from "redux-devtools-extension"

// 导入reducer
import reducers from './reducer';

// 创建仓库
const store = createStore(reducers, composeWithDevTools(applyMiddleware(thunk)))

// 导出仓库
export default store

创建reducer.js

// 导入模块
import { combineReducers } from 'redux-immutable';

// 导入reducer
// import {reducer as 模块名Reducer}from '../pages/模块名/store';
import {reducer as ArticlesReducer}from '../pages/articles/store';
// import {reducer as LoginReducer}from '../pages/login/store';

// 合并reducer
const reducers = combineReducers({
    // 模块小驼峰名:模块名Reducer大驼峰, 
    articles:ArticlesReducer, 
  
 
    // LoginReducer,
})

// 导出
export default reducers
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值