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)