redux的简单使用

redux不同与vuex,需要异步的话,需要用到thunk

1、创建需要用到的文件

第一步:src路径下创建目录文件 store,store下创建 index.js (用于创建store数据仓库),reducer.js(用于单独存储数据),actionTypes.js(用于存放action方法的type),actionCreators.js(用于存放action方法)、thunk.js(用于存放异步操作)

安装依赖:npm i redux

                  npm i redux-thunk // 异步

2、index.js

// 解构出 createStore()
import { createStore, applyMiddleware } from 'redux'

// 引入thunk
import thunk from 'redux-thunk';
// 引入reducer
import state from './reducer'

// 创建store数据仓库
let store = createStore(state, applyMiddleware(thunk))

export default store;

3、reducer.js

// 引入actionTypes
import { SET_STATE_MSG } from './actionTypes';

// state属性
const defaultState = {
    msg: '旧数据'
}

// 导出
export default (state = defaultState, actions) => {

    // set_State更改msg数据的方法
    if (actions.type == SET_STATE_MSG) {
        state.msg = actions.value
    }

    return state
}

4、actionTypes.js

// 更改msg数据的type标识
export const SET_STATE_MSG = 'set_state_msg'

5、actionCreators.js

// 更改msg数据的type标识
import { SET_STATE_MSG } from './actionTypes';

export let set_state_action = (value) => {
    return {
        type: SET_STATE_MSG,
        value
    }
}

6、thunk.js 

// 引入actionCreators
import { set_state_action } from './actionCreators';

// 使用 thunk【异步】
export const set_state_actionThunk = () => {
    return dispatch => {
        // 可以发送 axios 请求
        let data = '异步数据'
        dispatch(set_state_action(data))
    }
}

使用

import React, { Component } from 'react';
import './index.css'

// 引入store
import store from '../../store';
// 如果是同步 引入actionCreators  如果有异步需求 引入thunk.js  注意下边点击按钮时方法的名字要
// import { set_state_action } from '../../store/actionCreators';
import { set_state_actionThunk } from '../../store/thunk';

class index extends Component {

    state = { }
    // 构造器
    constructor() {
        super();
        store.subscribe(this.set_state_action_add)
    }

    // 设置store中的state到组件中的state
    set_state_action_add = () => {
        this.setState({
            name: '1'
        })
    }

    render() {
        return (
            <div>
                <h2>state数据:{store.getState().msg}</h2>
                <button onClick={() => store.dispatch(set_state_actionThunk())}> 改变state数据</button>
            </div >
        );
    }
}

export default index

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值