react-redux实战小笔记

redux 应该是非常有用的。虽然学习起来挺费劲的,还是值得学下。我根据学习的做个小笔记,免的忘了。

首先要安装第三方插件依赖,主要用到下面几个:
第一:yarn add redux react-redux 这是两个,一个是redux 一个是针对react的redux.
第二:yarn add redux-thunk 这个东西是中间件,都说特别好用。
第三:yarn add babel-plugin-transform-decorators-legacy 装饰器,开发时,能让你开发处漂亮而又优雅的代码来。

对了,最好再安装个浏览器插件,redux-devtools 下载

开始就先从package.json说起吧。先把装饰器的插件配置进来。
也就是增加下面的plugins的一行代码。

"babel": {
    "presets": [
      "react-app"
    ],
    "plugins":["babel-plugin-transform-decorators-legacy"]
  },

接着就是改造index.js。
createStore是创建新的store用的,applyMiddleware()装饰中间件的,compose是连接参数用的。

thunk是redux-thunk中间件暴露的唯一的一个方法。

Provider,connect是react连接redux的两个新的接口。
Provider也是个组件只用一次,放在最外层,传递进去一个store。

counter是自己写在index-redux里面的reducer函数方法。
window.devToolsExtension是为了浏览器插件用到的函数。

import React from 'react';
import ReactDOM from 'react-dom';
import { createStore,applyMiddleware,compose } from 'redux'
import thunk from 'redux-thunk'
import { Provider } from 'react-redux'

import App2 from './app2'
import { counter } from './index-redux'

const store = createStore(counter,compose(
    applyMiddleware(thunk),
    window.devToolsExtension ? window.devToolsExtension():f=>f)
)


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

reducer的函数,根据项目写自己的就行。
留个案例


const add_Gun = "Add_Gun"
const remove_Gun = "Remove_Gun"


export function counter(state=0,action){
    switch(action.type){
        case 'Add_Gun':
            return state+1
        case 'Remove_Gun':
            return state-1
        default :
            return 10
    }
}

export function Add_Gun(){
    return {type:add_Gun}
}

export function Remove_Gun(){
    return {type:remove_Gun}
}

// 异步加载,并且可以返回一个函数了。
export function Add_Gun_Async(){
    return dispatch=>{
        setTimeout(()=>{
            dispatch(Add_Gun())
        },2000)
    }
}

至于App组件的内容,肯定也是自己的内容。
也留下一个案例

import React, {Component} from 'react'
import {connect} from 'react-redux'
import {Add_Gun,Remove_Gun,Add_Gun_Async } from './index-redux'


@connect(
    // @符合是装饰器babel-plugin-transform-decorators-legacy实现的。
    //第一个参数是,你要state什么属性放到props里面
    state=>({num:state}),
    // 你要什么方法,把它放到props里,自动dispatch
    { Add_Gun,Remove_Gun,Add_Gun_Async }
    )
class App2 extends Component{
    render(){
        return(
            <div>
                <h2>现在有{this.props.num}把机关枪</h2>
                <button onClick={this.props.Add_Gun}>++机关枪++</button>
                <button onClick={this.props.Remove_Gun}>--机关枪--</button>
                <button onClick={this.props.Add_Gun_Async}>过2田还</button>

            </div>
        )
    }
}


export default App2

其实把上面3个文档下载下放到src里面,在本地就能跑起来看到效果了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值