redux & react-redux结合使用 2024
1.安装 redux react-redux
yarn add redux && yarn add react-redux
2.编写reducer
js
复制代码
const initstate={count:0}
exports.reducer=(state=initstate,action)=>{
switch (action.type){
case "add_action":
return {
count: state.count+1
}
default:
return state;
}
}
3.编写store
js
复制代码
import {createStore} from "redux";
import {reducer} from '../reducer'
const store=createStore(reducer)
export default store
4.根组件引入provider
js
复制代码
import Home from "./pages/home";
import ComA from "./pages/ComA";
import ComB from "./pages/ComB";
import store from "./store";
import {Provider} from "react-redux";
function App() {
return (
<Provider store={store}>
<div>
<ComA/>
<ComB/>
</div>
</Provider>
);
}
export default App;
5.发送状态
js
复制代码
import React from "react";
import {connect} from "react-redux";
class ComA extends React.Component{
handleClick=()=>{
console.log(111)
this.props.sendAction()
}
render() {
return (
<button onClick={this.handleClick}>+</button>
)
}
}
const mapDispatchToProps=(dispatch)=>{
return {
sendAction:()=>{
dispatch({
type:'add_action'
})
}
}
}
export default connect(null,mapDispatchToProps)(ComA)
6.接收状态
js
复制代码
import React from "react";
import {connect} from "react-redux";
class ComB extends React.Component{
render() {
return (
<button>{this.props.count}</button>
)
}
}
const mapStateToProps=state=>{
return state
}
export default connect(mapStateToProps)(ComB)