观看此文档请先去查阅之前发布的 redux 的基本使用
1.问题
store.getState().name
actionCreatore[CHANGE_AGE](29);
2.解决问题 react-redux
3.使用react-redux
redux 的基本使用不变
npm install react-redux
import store from "./index";
import { CHANGE_NAME, CHANGE_AGE } from "./actionTypes";
export default {
[CHANGE_NAME](payload) {
const action = {
type: CHANGE_NAME,
payload,
};
store.dispatch(action);
},
[CHANGE_AGE](payload) {
const action = {
type: CHANGE_AGE,
payload,
};
store.dispatch(action);
},
};
// import store from "./index";
import { CHANGE_NAME, CHANGE_AGE } from "./actionTypes";
export default {
[CHANGE_NAME](payload) {
const action = {
type: CHANGE_NAME,
payload,
};
// store.dispatch(action);
return action;
},
[CHANGE_AGE](payload) {
const action = {
type: CHANGE_AGE,
payload,
};
// store.dispatch(action);
return action;
},
};
import React, { Component } from "react";
import Son1 from "./son1";
import Son2 from "./son2";
import store from "./store";
// 引入 Provider
import { Provider } from "react-redux";
console.log(store);
class reduceDemo extends Component {
state = {
show: true,
};
unshow = () => {
this.setState({ show: false });
};
render() {
return (
<Provider store={store}>
<p>reduceDemo</p>
<button onClick={this.unshow}>销毁Son1</button>
{this.state.show && <Son2></Son2>}
<Son1></Son1>
</Provider>
);
}
}
export default reduceDemo;
/* eslint-disable no-useless-constructor */
import React, { Component } from "react";
import store from "./store/index";
import actionCreatore from "./store/actionCreatore";
import { CHANGE_NAME, CHANGE_AGE } from "./store/actionTypes";
class Son1 extends Component {
render() {
return (
<div>
<h1>Son1</h1>
{store.getState().name} -- {store.getState().age}
<button
onClick={() => {
actionCreatore[CHANGE_AGE](29);
}}
>
改年龄
</button>
</div>
);
}
componentDidMount() {
// store.subscribe 再注册一个监听之后,会返回一个取消监听的函数
this.unsubscribe = store.subscribe(() => {
this.setState({});
});
}
componentWillUnmount() {
// 判断unsubscribe是否存在
this.unsubscribe && this.unsubscribe();
console.log("组件销毁");
}
}
export default Son1;
/* eslint-disable no-useless-constructor */
import React, { Component } from "react";
import { connect } from "react-redux";
import actionCreatore from "./store/actionCreatore";
import { CHANGE_NAME, CHANGE_AGE } from "./store/actionTypes";
import { bindActionCreators } from "redux";
class Son1 extends Component {
render() {
return (
<div>
<h1>Son1</h1>
{this.props.name} --- {this.props.age}
<button
onClick={() => {
this.props[CHANGE_AGE](88);
}}
>
改年龄
</button>
</div>
);
}
}
// connect 是一个函数
// 该函数接收两个参数 mapStateToProps,mapDispatchToProps
// 返回一个高阶组件
// mapStateToProps 将state映射到props里
// mapDispatchToProps 将dispath映射到props里
// bindActionCreators 会将 actionCreatore 中的方法隐射到 props 中,是mapDispatchToProps的优化方案,并且在执行props中的方法时,会自动执行dispatch
// export default connect((state) => state)(Son1);
export default connect(
(state) => state,
(dispatch) => bindActionCreators(actionCreatore, dispatch)
)(son2);