redux

redux入门案例

流程.png

1.构建一个action,通过创建一个函数,返回一个对象,一定要携带type属性

action/index.js
const sendAction = ()=>{
    return{
        type:'send_type',
        value:'我是一个action'
    }
}

module.exports = {
    sendAction
};

2.构建reducer,用来相应action,然后通过return把数据返回给store

reducer/index.js
const initState = {
    value: '默认值'
}
const reducer = (state = initState, action) => {
    console.log(state,action)
    switch (action.type) {
        case 'send_type':
            return Object.assign({}, state, action);
        default:
            return state
    }
}

module.exports = {
    reducer
}

3.利用createStore来构建store,构建的时候传入我们写好的reducer

import {createStore} from 'redux';

import {reducer} from '../reducer';

const store = createStore(reducer);

export default store;

4.利用store.subscribe()注册监听

//组件中的使用
import React from 'react';
import { sendAction } from '../../action';
import store from '../../store';

export default class Home extends React.Component {
    handleClick = () => {
        const action = sendAction();
        store.dispatch(action)
    }

    componentDidMount(){
        store.subscribe(()=>{
            console.log(store.getState())
            this.setState({ })
        })
    }

    render() {
        return (
            <>
            
{store.getState().value}
) } }

5.利用store.dispatch()发送一个action去触发监听,使用store.getState()就可以拿到值

你可能感兴趣的:(redux)