第一步:下载 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)