CODE

React-Redux-Example

REACT-REDUX 小例子

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

import { createStore, combineReducers, bindActionCreators } from 'redux';
import { connect, Provider } from 'react-redux'
class Counter extends React.Component {
    constructor(props) {
        super(props)
    }
    render() {
        const { a, add,decrement  } = this.props
        return (
            <div>
                <p style={{background:'red'}} onClick={() => add(1)}>{a}</p>
            </div>
        )
    }
}
/***Action****/
function add(number) {
    return {
        type: 'ADD',
        number
    }
}
function decrement(number) {
    return {
        type: 'DECREMENT',
        number
    }
}
/***connect***/
     /***注入State***/
function mapStateToProps(state) {
    return {
        a: state.a
    }
}
      /***注入Dispatch***/
function actionCreatorsToProps(dispatch) {
    return bindActionCreators({ add, decrement }, dispatch)
}
let Hello = connect(mapStateToProps, actionCreatorsToProps)(Counter);
/***Reducer***/
const defaulState = { a: 1 }
const reducer = (state = defaulState, action) => {
    switch (action.type) {
        case 'TEST': console.log(state, action);
        case 'ADD': return {a: state.a + action.number}
        case 'DECREMENT': return state;
        default: return state;
    }
};

const store = createStore(reducer);

const render = () => {
    ReactDOM.render(
        <Provider store={store}>
            <Hello />
        </Provider>,
        document.getElementById('root')
    );
};

render();
store.getState()
registerServiceWorker();

回复

This is just a placeholder img.