react-redux配合redux-actions使用小例子

时间:2020-9-11 作者:admin

一、代码

import React, { Component } from 'react';
import {createStore, bindActionCreators} from 'redux';
import ReactDom from 'react-dom';
import { connect, Provider } from 'react-redux';
import {createAction, handleAction} from 'redux-actions';

const INCREMENT = 'INCREMENT';        //action-type
const increment = createAction(INCREMENT);
//调用increment()返回一个对象{type: 'INCREMENT'}

// const increment = createAction(
//   'INCREMENT',
//   mount => mount,
//   () => ({admin: true})
// )

const defaultState = { count: 1 };

const reducer = handleAction(
  INCREMENT,
  (state, action) => ({
    count: state.count + action.payload
  }),
  defaultState
)

const store = createStore(reducer);

@connect(
  state => ({
    count: state.count
  }),
  {
    increment
  }
)

class App extends Component {
  constructor(props) {
    super(props);
  }

  handleClick() {
    let { increment } = this.props;
    increment(1);
    console.log(this.props.count);
  }
  render() {
    return (
      <button>
        <div onClick={this.handleClick.bind(this)}>
          click me!
        </div>
      </button>
    );
  }
}

// function mapStateToProps(state) {
//   return {
//     count: state.count
//   }
// }

// function mapDispatchToProps(dispatch) {
//   return {
//     actions: bindActionCreators({createAction}, dispatch)
//   }
// }

// var AppApp = connect(
//   mapStateToProps,
//   mapDispatchToProps
// )(App);
ReactDom.render(
  <Provider store={store}>
    <App/>
  </Provider> ,
  document.getElementById('root')
)
声明:本文内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎进行举报,并提供相关证据,工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。