react配置redux

第一步:下载 react-redux 和redux

npm i react-redux redux -D

第二步:src路径下新建store文件

 store文件下新建index.js文件

 
import { createStore } from "redux";
//引入公用的方法
import { SET_NSME } from './action'
 
    //传值 name:姓名    age:  年龄
function user(state = { name: 'blue', age: 18 }, action) {
    switch (action.type) {
        case SET_NSME:
            return {
                ...state,
                age: state.age + action.n,
                name: action.name
            }
        default:
            return state;
    }
}
export default createStore(user)

在store下新建action.js

//年龄
export const SET_AGE = 'set_age'
//姓名
export const SET_NSME='set_name'
//年龄  n 接收年龄
export function setAge(n) {
    return {
        type: SET_NSME,
        n: n
    }
}
//姓名  name 接收姓名
export function setName(name) {
    return {
        type: SET_NSME,
        name: name
    }
}

第三步:App.js主文件

        引入react-redux

import { connect } from 'react-redux';

 redux 建立连接

export default connect((props,state)=>Object.assign({},props,state),{})(App)

如图:

第四步:src路径下的index.js文件

引入react-redux

// 引入react-reux
import { Provider } from 'react-redux';
import store from './store';

 使用Provider将router包起来 如图:

第五步:src路径下新建page文件:

page文件下新建index.js文件

这个是年龄

import React, { Component } from 'react';
//引入react-redux
import { connect } from 'react-redux';
//引入公共方法
import { setAge } from '../store/action'
 
class Index extends Component {
    // constructor(...args) {
    //     super(...args);
 
    // }
//定义方法点击传参
    FnAge(){
        this.props.setAge(2)
    }
    render() {
        return (
            <div>
                年龄:{this.props.age}
                <button onClick={this.FnAge.bind(this)}>点击</button>
            </div>
        )
    }
}
//建立连接  调用方法
export default connect((props, state) => Object.assign({}, props, state), {
    setAge
})(Index)

  新建list.js 这是姓名  输入姓名点击提交

import { Component } from 'react';
import { connect } from 'react-redux'
 
import { setName } from '../store/action'
 
 
class List extends Component {
    // constructor(...args) {
    //     super(...args);
    // }
    FnName(ev) {
        const name = ev.target.parentNode.children[0].value
        this.props.setName(name)
    }
    render() {
        return (
            <div>
                当前名字:{this.props.name}
                <input type='text' />
                <button onClick={this.FnName.bind(this)}>搜索</button>
            </div>
        )
    }
}
export default connect((props, state) => Object.assign({}, props, state), {
    setName
})(List)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值