0919 NOTE

0919 NOTE

redux的简单使用

①安装:npm i redux

②引用举例:

//store.js
import {createStore} from ‘redux’
import reducer from./reducers’
export default createStore(reducer)
//reducer.js
const initState = 0;
export default function countReducer(preState=initState,action) {
    let {type,data} = action;
    return type==="increment" ? preState+data*1 : type==="decrement" ? preState-data : preState;
}
import React, { Component } from "react";
import store from "../../redux/store";

export default class Count extends Component {
    render() {
        return (
        <div>
            <h2>计算总和为:{store.getState()}</h2>
            <select ref={c=>this.selectNumber=c}>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            </select>
            &nbsp;&nbsp;
            <button onClick={this.computedAdd}>+</button>&nbsp;&nbsp;
            <button onClick={this.computedMinus}>-</button>&nbsp;&nbsp;
            <button onClick={this.computedOddPlus}>奇数时+</button>&nbsp;&nbsp;
            <button onClick={this.computedAsync}>异步+</button>&nbsp;&nbsp;
        </div>
        );
    };
    
    componentDidMount(){
      store.subscribe(()=>{
        this.setState({});
      })
    };

  computedAdd = () => {
    store.dispatch({data:this.selectNumber.value*1,type:"increment"});
  };
  computedMinus = () => {
    store.dispatch({data:this.selectNumber.value*1,type:"decrement"});
  };
  computedOddPlus = () => {
    store.getState() % 2 !== 0 ? 
    store.dispatch({data:this.selectNumber.value*1,type:"increment"}) : alert("当前数值非奇数")
  };
  computedAsync = () => {
    setTimeout(()=>{
      store.dispatch({data:this.selectNumber.value*1,type:"increment"});
    },500)
  };
}

总结:

(1).去除Count组件自身的状态
(2).src下建立:
-redux
-store.js
-count_reducer.js

(3).store.js:
1).引入redux中的createStore函数,创建一个store
2).createStore调用时要传入一个为其服务的reducer
3).记得暴露store对象

(4).count_reducer.js:
1).reducer的本质是一个函数,接收:preState,action,返回加工后的状态
2).reducer有两个作用:初始化状态,加工状态
3).reducer被第一次调用时,是store自动触发的,
传递的preState是undefined,
传递的action是:{type:’@@REDUX/INIT_a.2.b.4}

(5).在index.js中监测store中状态的改变,一旦发生改变重新渲染
备注:redux只负责管理状态,至于状态的改变驱动着页面的展示,要靠我们自己写。

redux的完整使用

新增文件:
1.count_action.js 专门用于创建action对象
2.constant.js 放置容易写错的type值

redux异步action

(1).明确:延迟的动作不想交给组件自身,想交给action
(2).何时需要异步action:想要对状态进行操作,但是具体的数据靠异步任务返回。
(3).具体编码:
1).yarn add redux-thunk,并配置在store中
2).创建action的函数不再返回一般对象,而是一个函数,该函数中写异步任务。
3).异步任务有结果后,分发一个同步的action去真正操作数据。
(4).备注:异步action不是必须要写的,完全可以自己等待异步任务的结果了再去分发同步action。

react-redux基本使用

(1).明确两个概念:
1).UI组件:不能使用任何redux的api,只负责页面的呈现、交互等。
2).容器组件:负责和redux通信,将结果交给UI组件。
(2).如何创建一个容器组件————靠react-redux 的 connect函数
connect(mapStateToProps,mapDispatchToProps)(UI组件)
-mapStateToProps:映射状态,返回值是一个对象
-mapDispatchToProps:映射操作状态的方法,返回值是一个对象
(3).备注1:容器组件中的store是靠props传进去的,而不是在容器组件中直接引入
(4).备注2:mapDispatchToProps,也可以是一个对象

import countUI from "../../components/Count";
import {connect} from "react-redux";
import {incrementAction,decrementAction,asyncIncrementAction} from "../../redux/count_action"

// let mapStateToProps = state => ({state})

// let mapDispatchToProps = dispatch => ({
//         increment : data => dispatch(incrementAction(data)),
//         decrement : data => dispatch(decrementAction(data)),
//         asyncIncrement : data => dispatch(asyncIncrementAction(data,500)),
//     })


// export default connect(mapStateToProps,mapDispatchToProps)(countUI);


// export default connect(
//     state => ({state}),
//     dispatch => ({
//         increment : data => dispatch(incrementAction(data)),
//         decrement : data => dispatch(decrementAction(data)),
//         asyncIncrement : data => dispatch(asyncIncrementAction(data,500)),
//     })
// )(countUI);

export default connect(
    state => ({state}),
    {
        increment : incrementAction,
        decrement : decrementAction,
        asyncIncrement : asyncIncrementAction,
    }
)(countUI);
import React, { Component } from "react";
// import store from "../../redux/store";

// import {incrementAction,decrementAction,asyncIncrementAction} from "../../redux/count_action";

export default class Count extends Component {
    render() {
      // console.log(this.props);
        return (
        <div>
            <h2>计算总和为:{this.props.state}</h2>
            <select ref={c=>this.selectNumber=c}>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            </select>
            &nbsp;&nbsp;
            <button onClick={this.computedAdd}>+</button>&nbsp;&nbsp;
            <button onClick={this.computedMinus}>-</button>&nbsp;&nbsp;
            <button onClick={this.computedOddPlus}>奇数时+</button>&nbsp;&nbsp;
            <button onClick={this.computedAsync}>异步+</button>&nbsp;&nbsp;
        </div>
        );
    };

    // componentDidMount(){
    //   store.subscribe(()=>{
    //     this.setState({});
    //   })
    // };

  computedAdd = () => {
    // store.dispatch(incrementAction(this.selectNumber.value*1));
    this.props.increment(this.selectNumber.value*1);
    
  };
  computedMinus = () => {
    // store.dispatch(decrementAction(this.selectNumber.value*1));
    this.props.decrement(this.selectNumber.value*1);
  };
  computedOddPlus = () => {
    // store.getState() % 2 !== 0 ? 
    // store.dispatch(incrementAction(this.selectNumber.value*1)) : alert("当前数值非奇数")
    this.props.state % 2 !== 0 ?
    this.props.increment(this.selectNumber.value*1) : alert("当前数值非奇数");
  };
  computedAsync = () => {
      // store.dispatch(asyncIncrementAction(this.selectNumber.value*1,500));
      this.props.asyncIncrement(this.selectNumber.value*1,500)
  };
}

react-redux优化

(1).容器组件和UI组件整合一个文件
(2).无需自己给容器组件传递store,给包裹一个即可。
(3).使用了react-redux后也不用再自己检测redux中状态的改变了,容器组件可以自动完成这个工作。
(4).mapDispatchToProps也可以简单的写成一个对象
(5).一个组件要和redux“打交道”要经过哪几步?
(1).定义好UI组件—不暴露
(2).引入connect生成一个容器组件,并暴露,写法如下:
connect(
state => ({key:value}), //映射状态
{key:xxxxxAction} //映射操作状态的方法
)(UI组件)
(3).在UI组件中通过this.props.xxxxxxx读取和操作状态

import React, { Component } from "react";
import {connect} from "react-redux";
import {incrementAction,decrementAction,asyncIncrementAction} from 

class Count extends Component {
    render() {
        return (
        <div>
            <h2>计算总和为:{this.props.state}</h2>
            <select ref={c=>this.selectNumber=c}>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            </select>
            &nbsp;&nbsp;
            <button onClick={this.computedAdd}>+</button>&nbsp;&nbsp;
            <button onClick={this.computedMinus}>-</button>&nbsp;&nbsp;
            <button onClick={this.computedOddPlus}>奇数时+</button>&nbsp;&nbsp;
            <button onClick={this.computedAsync}>异步+</button>&nbsp;&nbsp;
        </div>
        );
    };

  computedAdd = () => {
    this.props.increment(this.selectNumber.value*1);
  };
  computedMinus = () => {
    this.props.decrement(this.selectNumber.value*1);
  };
  computedOddPlus = () => {
    this.props.state % 2 !== 0 ?
    this.props.increment(this.selectNumber.value*1) : alert("当前数值非奇数");
  };
  computedAsync = () => {
      this.props.asyncIncrement(this.selectNumber.value*1,500)
  };
}

export default connect(
    state => ({state}),
    {
        increment : incrementAction,
        decrement : decrementAction,
        asyncIncrement : asyncIncrementAction,
    }
)(Count);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

菜鸟小胖砸

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值