react使用总结四:react 使用react-redux

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/bbsyi/article/details/82493135

redux相当于vue中的vuex。

1.安装依赖

cnpm i redux --save

cnpm i react-redux --save

2.reducer.js 主要传入state和action

const themeReducer = (state, action) => {
    if (!state) return {
      themeColor: 'red'
    }

    switch (action.type) {
      case 'CHANGE_COLOR':
        return { ...state, themeColor: action.themeColor }
      default:
        return state
    }
}
export default themeReducer

3.themeSwitch.js 使用

import React, { Component } from 'react';
import {Router,Route,browserHistory} from 'react-router-dom';
// 1.引入PropTypes
import PropTypes from 'prop-types';
// 2.引入connect
import { connect } from 'react-redux';

class ThemeSwitch extends Component {

// 3.定义propTypes
	static propTypes = {
	    themeColor: PropTypes.string,
	    onSwitchColor: PropTypes.func
	 }

	constructor(props) {
		super(props);
   	}


   	// 生命周期
	componentWillMount(){
		
	}

	// {/*7.使用*/}
	handleSwitchColor (color) {
	    if (this.props.onSwitchColor) {
	      this.props.onSwitchColor(color)
	    }
	}


  	render() {
	    return (
	      <div>
	      {/*7.使用*/}
	        <button style={{ color: this.props.themeColor }}
	          onClick={this.handleSwitchColor.bind(this, 'red')}>Red</button>
	        <button
	          style={{ color: this.props.themeColor }}
	          onClick={this.handleSwitchColor.bind(this, 'blue')}>Blue</button>
	      </div>
	    );
	}

}

// 4.定义mapStateToProps
const mapStateToProps = (state) => {
	return {
		themeColor: state.themeColor
	}
}
// 5.定义mapDispatchToProps
const mapDispatchToProps = (dispatch) => {
	return {
		onSwitchColor:(color) => {
			dispatch({ type: 'CHANGE_COLOR', themeColor: color })
		}
	}
}

// 6.connect连接
ThemeSwitch = connect(mapStateToProps, mapDispatchToProps)(ThemeSwitch);

export default ThemeSwitch;

参考:https://blog.csdn.net/bbsyi/article/details/82426733

猜你喜欢

转载自blog.csdn.net/bbsyi/article/details/82493135