记一次React_Redux的操作

MyComponent

import React, {Component} from 'react';

export default class MyComponent extends Component {
    render() {
        return (
            

{this.props.count}

); } }

reducer

function reducer(state={
    count:10
},action) {
    switch (action.type) {
        case 'add':
            return {
                ...state,
                count: state.count+1
            }
        case 'substract':
            return {
                ...state,
                count: state.count-1
            }
        case 'toZero':
            return {
                ...state,
                count: 0
            }
        default:
            return state
    }
}

export default reducer;

App

//state/props
import myComponent from "./myComponent";
import {connect} from 'react-redux'

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

//function
function mapDispatchToProps(dispatch) {
    return{
        add:()=>dispatch({
           type:'add'
        }),
        substract:()=>dispatch({
            type:'substract'
        }),
        toZero:()=>dispatch({
            type:'toZero'
        })
    }
}


//connect  联系在一起的语法
const App = connect(mapStateToProps,mapDispatchToProps)(myComponent)

export default App

index

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import {Provider} from "react-redux";
import {createStore} from "redux";
import reducer from "./reducer";


//创造store工厂
const store = createStore(reducer)

ReactDOM.render(
    
        
    ,
    document.getElementById('root')
)

 

你可能感兴趣的:(React)