You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
75 lines
1.9 KiB
75 lines
1.9 KiB
import React, { Component } from 'react'; |
|
import { connect } from 'react-redux'; |
|
|
|
class String extends Component { |
|
state = { } |
|
handleAdd = () => { |
|
this.props.add(10); |
|
} |
|
|
|
handleSub = () => { |
|
this.props.sub(20); |
|
} |
|
render() { |
|
return ( |
|
<React.Fragment> |
|
<h3>String组件: </h3> |
|
<div>{this.props.string}</div> |
|
<button className='btn btn-success' style={{marginRight: "10px"}} onClick={this.handleAdd}>add</button> |
|
<button className='btn btn-info' onClick={this.handleSub}>sub</button> |
|
</React.Fragment> |
|
); |
|
} |
|
} |
|
|
|
// 将store保存的state值绑定到this.props |
|
// state |
|
// / \ |
|
// string number |
|
const mapStateToProps = (state,props) => { |
|
return { |
|
string: state.string, // 将string的state值赋给props的string属性 |
|
} |
|
} |
|
|
|
|
|
|
|
// reducer: 对当前数据进行操作: 返回操作之后的数据 |
|
// 传入参数为 (state,action), 根据action对原数据state执行不同的操作 |
|
// 例如下面的f1,原始数据为state=0,有增减两种操作 |
|
// reducer: f1 |
|
|
|
// const f1 = (state = 0, action) => { |
|
// switch (action.type) { |
|
// case 'add': |
|
// return state + action.value; |
|
// case 'sub': |
|
// return state - action.value; |
|
// default: |
|
// return state; |
|
// } |
|
// } |
|
|
|
|
|
// String组件想修改Number组件中的值 |
|
// dispatch会递归调用所有reducer函数 |
|
|
|
const mapDispatchToProps = { |
|
// 绑定到props的add中 |
|
add: (n) => { |
|
// dispatch中传入的action |
|
return { |
|
type: 'add', |
|
value: n, |
|
} |
|
}, |
|
sub: (n) => { |
|
return { |
|
type: 'sub', |
|
value: n, |
|
} |
|
} |
|
} |
|
|
|
// 使用connet绑定String组件并返回一个新组件 |
|
export default connect(mapStateToProps,mapDispatchToProps)(String); |