react-redux 入门示例教程

作者: MJ 分类: react 发布时间: 2018-11-15 17:42

最近在研究react-redux,这个理念其实到现在还是没有彻底研究透彻,但是大致明白点了,做一个梳理,怕自己忘了,也自己整理一下思绪。

actions.js

const jia = {
  type:"ADD"
}

const jian = {
  type:"DEL"
}

const majiang = {
  type:"MJ"
}
export {jia, jian , majiang};

reducers.js

const num = 1000;
const reducer = (state=num,action)=>{
  switch (action.type){
    case "ADD":
      return state += 1000;
    case "MJ":
      return state += 20000;
    case "DEL":
        if(state <= 0){
          alert("不能小于0")
          return 0
        }else{
          return state -= 1000;
        }
    default:
      return state;
  }
}

export default reducer;

other.js

import React, { Component } from 'react';
import { connect } from 'react-redux';
import {jia,jian,majiang} from './../redux/actions'
class Other extends Component{
    
      render() {
        const { PayIncrease, PayDecrease,Majiang } = this.props;
        return (
          <div className="App">
            <h2>other</h2>
            <div className="App">
              <h2>当月工资为{this.props.num}</h2>
              <button onClick={PayIncrease}>升职加薪</button>
              <button onClick={PayDecrease}>迟到罚款</button>
              <button onClick={Majiang}>打印名字</button>
            </div>
          </div>
        );
      }
}
//需要渲染什么数据
function mapStateToProps(state) {
  return {
      num:state
  }
}
//需要触发什么行为
function mapDispatchToProps(dispatch) {
  return {
      PayIncrease: () => dispatch(jia),
      PayDecrease: () => dispatch(jian),
      Majiang :()=> dispatch(majiang)
  }
}
  
export default connect(mapStateToProps, mapDispatchToProps)(Other);

home.js

import React, { Component } from 'react';
// import {Link} from 'react-router-dom'
import Other from './other'
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import reducer from '../redux/reducers'
//创建store
const store = createStore(reducer);

class Home extends Component{
    render(){
        return (
            <div>
                首页
                {/* <Link to='/other'>其他页面</Link> */}
                <Provider store={store}>
                <Other></Other>   
                </Provider>
            </div>
        )
    }
}
export default Home;

 

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!

发表评论

电子邮件地址不会被公开。 必填项已用*标注