React入门 (5) - Redux & React-Redu

2021-02-21  本文已影响0人  申_9a33

redux

安装 npm i redux

api介绍

1. src\ReduxStore.js

import { createStore } from 'redux';

function counterReducer(state = 0, action) {
    switch (action.type) {
        case "ADD":
            state += action.payload
            break;

        default:
            break;
    }

    return state
}

export default createStore(counterReducer)

2.src\page\ReduxPage.js

import React, { Component } from 'react'
import store from '../ReduxStore';


export default class ReduxPage extends Component {

    componentDidMount() {
        store.subscribe(() => {
            this.forceUpdate();
        })
    }

    add = () => {
        store.dispatch({ type: "ADD", payload: 2 })
    }

    render() {
        return (
            <div>
                <h3>Redux Page</h3>
                <div>{store.getState()}</div>
                <button onClick={this.add}>add</button>
            </div>
        )
    }
}

react-redux

安装 npm i react-redux

api

1.src\index.js

import React from 'react';
import ReactDOM from 'react-dom';
import reportWebVitals from './reportWebVitals';
import { Provider } from 'react-redux'
import store from './ReduxStore';
import ReactReduxPage from './page/ReactReduxPage';

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      <ReactReduxPage />
    </Provider>
  </React.StrictMode>,
  document.getElementById('root')
);

2.src\page\ReactReduxPage.js

import React, { Component } from 'react'
import { connect } from 'react-redux'

class ReactReduxPage extends Component {
    render() {
        console.log(this.props);
        const { state, add } = this.props

        return (
            <div>
                <h3>ReactReduxPage</h3>
                <div>{state}</div>
                <button onClick={() => add(1)}>btn</button>
            </div>
        )
    }
}

const mapStateToPropsParam = state => {
    return {
        state
    }
}

const mapDispatchToPropsParam = {
    add: (v) => {
        return { type: "ADD", payload: v }
    }
}

export default connect(
    mapStateToPropsParam, // 状态映射
    mapDispatchToPropsParam // 派发事件映射
)(ReactReduxPage);

源码

上一篇 下一篇

猜你喜欢

热点阅读