本质理解:
组件A和B通过一个公共对象上C进行通信 ,
A更新后,通知C,C相当于一个接线员 ,通过reducer,来决定收到消息发给谁, 收到的数据存在store中,达到双向通向的目的
关键代码
comA/index.js
import React, { Component } from 'react'
import { connect } from 'react-redux'
class ComA extends Component {
handleClick = ()=>{
console.log("ComA",this.props);
this.props.sendAction();
}
render() {
return (
<div>
<button onClick={this.handleClick} type="">+</button>
</div>
)
}
}
const mapDispatchToprops = (dispatch)=>{
return {
sendAction:()=>{
dispatch({
type:"add_action"
})
}
}
}
export default connect(null,mapDispatchToprops)(ComA);
comB/index.js
import React, { Component } from 'react'
import { connect } from 'react-redux'
class ComB extends Component {
render() {
console.log("ComB props",this.props)
return (
<div> {this.props.count} </div>
)
}
}
const mapStateToProps = state=>{
console.log(state);
return state;//这里把state返回给了ComB的props
}
export default connect(mapStateToProps)(ComB);
redurer/index.js
const initState={
count:10
}
exports. reducer = (state = initState,action)=>{
console.log(initState,action,state);
// return initState;
switch(action.type){
case "add_action":
console.log("+1",state);
return {
count:state.count+1
}
default:
return state;
}
}
App.js
import Home from "./pages/home/index"
import ComA from "./pages/comA";
import ComB from "./pages/comB";
import { Provider } from "react-redux";
import store from "./store";
function App() {
return (
<Provider store={store}>
<div className="App">
<Home />
<ComA />
<ComB />
</div>
</Provider>
);
}
export default App;
store/index.js
import { createStore } from "redux";
import {reducer} from "../reducer/index"
const store = createStore(reducer);
export default store;