React-Redux的基本使用:
由于使用了React-Redux中的connect,不用再关注react的再次渲染,所以不需要写以下代码:
store.subscribe(()=>{
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
)
})
(1)UI组件的创建:src----components----count----index.jsx
import React, { Component } from 'react'
export default class Count extends Component {
add = () => {
const {value} = this.selectedNumber
// store.dispatch(createIncrementAction(value*1))
this.props.jia(value*1)
}
remove = () => {
}
addtwo = () => {
const {value} = this.selectedNumber
}
render() {
console.log(this.props)
return (
<div>
<h1>当前求和为:{this.props.count}</h1>
<select ref={(c)=>this.selectedNumber = c}>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button onClick={this.add}>+</button>
<button onClick={this.remove}>-</button>
<button>当前求和为奇数再加</button>
<button onClick={this.addtwo}>异步加</button>
</div>
)
}
}
(2)容器组件Count的创建:src----containers----count----index.jsx
// 引入countUI组件
import CountUI from '../../components/count'
// 引入connect用于连接UI组件与redux
import {connect} from 'react-redux'
import store from '../../redux/store'
// 在第二个括号中将UI组件给传进去
// 第一个括号里需要传两个参数
// 这样的做法是<CountUI n={100} />
// store的状态不需要你写store.getstate()
// 他已经把store.getstate()这个返回值传给了state
// 所以只需要把state这个值给了count就可以了
function mapStateToProps (state) {
return {count:state}
}
function mapDispatchToProps () {
return {jia:(data)=>{
console.log(data)
// 通知redux执行加法
store.dispatch({type:'increment',data})
}}
}
const CountContainer = connect(mapStateToProps,mapDispatchToProps)(CountUI)
// a函数的返回值作为状态传递给了UI组件
export default CountContainer
在app.js中以传props的方式:
import CountContainer from './containers/count'
import store from './redux/store'
function App() {
return (
<div>
<CountContainer store={store}/>
</div>
);
}
export default App;
容器组件中mapStateToProps,mapDispatchToProps的一般写法与优化写法:
如果有多个容器组件的时候,不用给每个容器组件标签传store,只需要在入口index.js文件中引入Provider,如下述代码所示:
import {Provider} from 'react-redux'
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);