【发布时间】:2021-08-30 00:08:39
【问题描述】:
我在下面有一段代码在转换为 HOC 组件之前运行良好:
class Filters extends React.Component {
componentDidMount() {
const { store } = this.context;
this.unsubscribe = store.subscribe(() => this.forceUpdate());
}
componentWillUnmount() {
this.unsubscribe();
}
render() {
const { store } = this.context;
const currentFilter = store.getState().visibilityFilter;
const tags = ["All", "Active", "Completed"];
return (
<>
Show:{" "}
{tags.map((t, index) => {
if (t === currentFilter) {
return (
<a href="#">
{t + " "}
{index === 2 ? " " : ","}
</a>
);
}
return (
<a
onClick={() => {
store.dispatch({
type: "SET_VISIBILITY_FILTER",
filter: t
});
}}
>
{t + " "}
{index === 2 ? " " : ","}
</a>
);
})}
</>
);
}
}
Filters.contextTypes = {
store: React.PropTypes
};
我将它更改为如下所示的 HOC 组件,但它不起作用,也没有错误通知。此代码来自规范教程 todolist 来自 reduxjs 官方文档。我检查了反应官方文档 https://reactjs.org/docs/higher-order-components.html 并没有发现任何异常不遵守它的规则。有谁知道什么是错误?
const Originfilters = ({ currentFilter, handleClick = (f = f) }) => {
const tags = ["All", "Active", "Completed"];
return (
<>
Show:{" "}
{tags.map((t, index) => {
if (t === currentFilter) {
return (
<a href="#">
{t + " "}
{index === 2 ? " " : ","}
</a>
);
}
return (
<a
onClick={(t) => {
handleClick(t);
}}
>
{t + " "}
{index === 2 ? " " : ","}
</a>
);
})}
</>
);
};
class Filters extends React.Component {
componentDidMount() {
const { store } = this.context;
this.unsubscribe = store.subscribe(() => this.forceUpdate());
}
componentWillUnmount() {
this.unsubscribe();
}
render() {
const { store } = this.context;
return (
<Originfilters
currentFilter={store.getState().visibilityFilter}
handleClick={(filter) => {
store.dispatch({
type: "SET_VISIBILITY_FILTER",
filter
});
}}
/>
);
}
}
Filters.contextTypes = {
store: React.PropTypes
};
【问题讨论】:
-
这是一个学习项目吗?你真的不应该在生产中使用这样的代码,因为你实际上是在重新创建 react-redux 库,但是该库已经有大约 6 年的学习和优化你错过了。
-
是的,这是一个来自 egghead.io 的学习项目,导师是 redux 的创建者 Dan Abramov。谢谢你的建议,我想这个逻辑现在已经过时了。