react使用redux

121 阅读1分钟

1.开发环境 react+redux
2.电脑系统 windows10专业版
3.在使用react开发的过程中,我根据项目的项目可能会使用到状态管理工具,在这里我选择的是 redux,下面我分享一下在react怎么十一redux!
4.在src目录下面新建 action/reducer/Stroe 文件夹,结构如下:

5.action/index代码如下:

/*
我是一个action的对象
*/

const sendAction=(aa)=>{
    return{
        type:"send_action",
        chen:aa
    }
}

module.exports={
    sendAction
}

6.reducer/index代码如下:

/*
这个文件是创建 reducer 函数的,专门处理 发送过来的 action
*/

const initState = {
    chen: '默认值'
}

const reducer = (state = initState, action) => {
    console.log("resucer:",state,action);
    switch (action.type) {
        case "send_type":
            return Object.assign({}, state, action);
        default:
            return state;
    }
}

module.exports = {
    reducer
}

7.Store/index代码如下:

import { createStore } from "redux";
import {reducer} from '../reducer/index'
const store=createStore(reducer);
export default store;

8.在react模板中添加如下代码:

import React from "react";
import store from '../Store';
import {sendAction} from '@/action'
export default class Home extends React.Component {
    constructor(props) {
        super(props);

        // 这个bind方法是必须的,以确保`this`可以在回调函数handleClick中使用
    this.chenget = this.chenget.bind(this);
    }
    // 页面已加载 就请求数据
    chenget(){
        console.log("我是state的数据");
        console.log(store.getState());
        console.log("我是state的数据结束啦");
    }
    componentDidMount(){
    }

    dian =()=>{
        const aa=100;
        const action= sendAction(aa);
        store.dispatch(action);
        //在这里我们看到了,我们在 redux 中定义的chen变量的值被修改了
    }

    render() {
        //用一个变量,接受
        const ChenHome =
            <div>
                <p> 我是home </p>
                <p> 我要坏加 </p>
                <a href="#/about" > 去about </a>
                <p onClick={this.dian}>会哦加</p>
            </div>
        //结束啦
        return (ChenHome
        )
            ;
    }
}

9.效果如图:

//根据图,我们可以得知,在reducer/index中定义的chen变量被修改啦
10.本期的教程到了这里就结束啦,是不是很nice,让我们一起努力走向巅峰!