image.png
組件目錄結(jié)果
image.png
components: Count/ index.jsx
import React, { Component } from 'react'
//引入action
import {
increment,
decrement,
incrementAsync
} from '../../redux/actions/count'
//引入connect用于連接UI組件與redux
import {connect} from 'react-redux'
//定義UI組件
class Count extends Component {
state = {carName:'奔馳c63'}
//加法
increment = ()=>{
const {value} = this.selectNumber
this.props.increment(value*1)
}
//減法
decrement = ()=>{
const {value} = this.selectNumber
this.props.decrement(value*1)
}
//奇數(shù)再加
incrementIfOdd = ()=>{
const {value} = this.selectNumber
if(this.props.count % 2 !== 0){
this.props.increment(value*1)
}
}
//異步加
incrementAsync = ()=>{
const {value} = this.selectNumber
this.props.incrementAsync(value*1,500)
}
render() {
//console.log('UI組件接收到的props是',this.props);
return (
<div>
<h2>我是Count組件,下方組件總?cè)藬?shù)為:{this.props.renshu}</h2>
<h4>當(dāng)前求和為:{this.props.count}</h4>
<select ref={c => this.selectNumber = c}>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button onClick={this.increment}>+</button>
<button onClick={this.decrement}>-</button>
<button onClick={this.incrementIfOdd}>當(dāng)前求和為奇數(shù)再加</button>
<button onClick={this.incrementAsync}>異步加</button>
</div>
)
}
}
//使用connect()()創(chuàng)建并暴露一個Count的容器組件
export default connect(
state => ({
count:state.count,
personCount:state.persons.length
}),
{increment,decrement,incrementAsync}
)(Count)
components: Person/ index.jsx
import React, { Component } from 'react'
import {nanoid} from 'nanoid'
import {connect} from 'react-redux'
import {addPerson} from '../../redux/actions/person'
class Person extends Component {
addPerson = ()=>{
const name = this.nameNode.value
const age = this.ageNode.value*1
const personObj = {id:nanoid(),name,age}
this.props.addPerson(personObj)
this.nameNode.value = ''
this.ageNode.value = ''
}
render() {
return (
<div>
<h2>我是Person組件,上方組件求和為{this.props.count}</h2>
<input ref={c=>this.nameNode = c} type="text" placeholder="輸入名字"/>
<input ref={c=>this.ageNode = c} type="text" placeholder="輸入年齡"/>
<button onClick={this.addPerson}>添加</button>
<ul>
{
this.props.persons.map((p)=>{
return <li key={p.id}>{p.name}--{p.age}</li>
})
}
</ul>
</div>
)
}
}
export default connect(
state => ({
persons:state.persons,
count:state.count
}),//映射狀態(tài)
{addPerson}//映射操作狀態(tài)的方法
)(Person)
redux : action reducers constant.js store.js
action/ count.js
image.png
action/ person.js
image.png
reducers/ count.js
image.png
reducers/ person.js
image.png
reducers/ index.js
image.png
redux/ constant.js
image.png
redux/ store.js
image.png
app.jsx
image.png
index.js
image.png