【发布时间】:2020-06-19 01:39:43
【问题描述】:
以下代码的目标是呈现从表中的 observable 接收到的引号。 我有两个版本的代码,一个是使用 hooks 和 useEffect 的反应函数,另一个是使用 setState 和 componentDidMount 和 componentWillUnmount 的反应类。使用 react 函数,引号根本不显示。使用 react 类,表格会不断更新。如果我对该功能做错了什么,那是什么?如果我使用正确,那么 hooks 和 useEffect 不起作用,componentDidMount/willUnmount 起作用有什么区别?
功能:
function DisplayQuotes() {
const [storedQuotes, setQuotes] = useState({});
useEffect(() => {
let subscription = SymbolsObservable.subscribe(setQuotes);
return () => subscription.unsubscribe();
}, [storedQuotes, setQuotes]);
return (
<div>
<QuotesTable values={storedQuotes} />
</div>
);
}
类:
class DisplayQuotes extends React.Component {
constructor(props) {
super(props);
this.state = { storedQuotes: {} };
}
componentDidMount() {
this.subscription = SymbolsObservable.subscribe((quotes) =>
this.setState({ storedQuotes: quotes })
);
}
componentWillUnmount() {
this.subscription.unsubscribe();
}
render() {
return (
<div>
<QuotesTable values={this.state.storedQuotes} />
</div>
);
}
}
【问题讨论】:
-
您如何将
componentDidMount、componentWillUnmount和setState的功能与基于类的组件共享以避免重复? -
不知道你的意思,抱歉有点新反应:) 如果你问为什么要作为一个班级来做这件事,这就是为什么我试图弄清楚为什么这个函数不起作用