redux 与 react-redux

  • Redux

一、Redux 三大原则:

  1、一个应用永远只有一个数据源(整个应用状态都保存在一个对象中,Redux提供的工具函数combineReducers可以解决庞大的数据对象的问题)

  2、状态是只读的,不能直接修改,而是派发action

  3、状态修改均由reducer 这样的纯函数完成

二、在项目中使用

  1、在项目入口文件中import

      --------若没有则需要安装,ts语法下安装使用 npm install @types/redux的方式

import { createStore, applyMiddleware } from "redux";

  2、创建store 

// App 是使用combineReducers方法生成的容器组件,里面融合了多个reducer
export const store = createStore(App, applyMiddleware(thunk));
  ReactDOM.render(
  <Provider store={store}>
    <BrowserRouter>
      <Configurator />
    </BrowserRouter>
  </Provider>,
  document.getElementById("root") as HTMLElement
);

  createStore方法创建的是一个对象,它本身又包含4个方法

  getState():获取store中的数据 及 状态

  dispatch(action):分发一个action ,并返回整个action,这是唯一能改变store中数据的方式

  subscribe(listener):注册一个监听者,它在store发生变化时被调用

  • React-Redux

1、与redux一样在项目入口文件中import并使用

2、在项目中使用时与redux则不同,react-redux提供了 connect()方法:export default connect(mapStateToProps, mapDispatchToProps)(Form.create()(ScheduleList));

 

   来获取store数据的功能

  

// 从store 中取数据,此时的this.props包含的有(父组件传过来的数据)和(在这个方法中获取到的数据)
const mapStateToProps = (state) => {
    return ({
        count: state.counter.count
    })
}
// 派发action改变store数据,这里边不能调用这个外边的类中的其他方法,可以在其它方法中以this.props.func()的方法调用这里边派发action的方法,  注:ownProps为别的组件传过来的属性或方法

const mapDispatchToProps=(dispatch,ownProps)=>{
    return{
        handleInputFocus(){
            dispatch(actionCreaters.getList());
            dispatch(actionCreaters.searchFocus());
        },
        handleInputBlur(){
            dispatch(actionCreaters.searchBlur());
        },
        handleMouseEnter(){
            dispatch(actionCreaters.mouseEnter());
        },
        handleMouseLeave(){
            dispatch(actionCreaters.mouseLeave());
        },
        handleChangePage(page,totalPage){
            if(page < totalPage){
                dispatch(actionCreaters.changePage(page + 1));
            }else{
                dispatch(actionCreaters.changePage(1));
            }
            
        }
    }
}

 

转载于:https://www.cnblogs.com/lal-z/p/10451645.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值