美文网首页
React入门 (5) - Redux & React-Redu

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

作者: 申_9a33 | 来源:发表于2021-02-21 12:54 被阅读0次

redux

安装 npm i redux

api介绍

  • createStore 创建store
  • reducer 初始化,修改状态函数
  • getState 获取状态值
  • dispatch 提交更新
  • subscribe 订阅变更

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

  • Provider 为后代组件提供store
  • connect 为组件提供数据和变更的方法

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);

源码

相关文章

网友评论

      本文标题:React入门 (5) - Redux & React-Redu

      本文链接:https://www.haomeiwen.com/subject/xshnxltx.html