高阶组件
import { Switch } from "antd-mobile"
import './index.styl'
import store from '@/redux/store'
export default function withHeader(WrappedComponent, title, selector) {
return class HOC extends React.Component {
state = {
checked: false
}
handleChange = (c) => {
this.setState({
checked: c
})
store.dispatch(selector(c))
}
render() {
const { checked } = this.state
const props = Object.assign({},this.props,{handleChange:this.handleChange})
return (
<div className="common-module">
<div className="header-title">
<div className="title">{title}</div>
<Switch
onChange={c => this.handleChange(c)}
checked={checked}
/></div>
{checked ? <div className="content"><WrappedComponent {...props} /></div> : <></>}
</div>
);
}
};
}
被包裹的组件
import { connect } from "react-redux";
import { addBoutique, toggleBoutique } from "@/redux/actions/boutique";
import withHeaderTitle from "@/components/header-title";
function Finance(props) {
const addBoutique = () => {
props.addBoutique({
name: "精品2",
price: 3500,
});
};
return (
<>
<div>优选精品</div>
{props.boutique.list.map((item, index) => {
return (
<div key={index}>
{item.name}---{item.price}
</div>
);
})}
<button onClick={addBoutique}>添加精品</button>
</>
);
}
export default connect(
(state) => ({
boutique: state.boutique,
}), //映射状态
{ addBoutique, toggleBoutique } //映射操作状态的方法
)(
withHeaderTitle(Finance, "优选精品", toggleBoutique)
);
这是我开发的一个高阶组件,目的是为了实现下面的效果
因为页面中类似的组件很多,所以我就想把公共的头部抽离出来,放到高阶组件里面,然后当switch为true的时候,下面的东西(被高阶组件包裹的组件)才展示出来。
最终该页面的数据需要提交到后端,所以我们需要拿到当前模块switch是否为true,而当前模块的所有信息,我都是在redux里面初始化的,改变时实时存储到redux里面去,最终提交的数据都是从redux中取。
目前有三个问题:
1.我这样抽离高阶组件是否合理?把switch这个切换逻辑放到高阶组件里面?
2.因为高阶组件里面的state是固定写死的,我希望高阶组件里面的state中的checked数据是来源于redux的,因为是多个组件在使用这个高阶组件,我也不能直接从store里面去取,现在在高阶组件我无法拿到对应的redux初始化是否选中的值,这个应该怎么取呢?
3.我在高阶组件里面的事件里面直接调用了store.dispatch(),这种写法是否合理?