【问题标题】:What are the differences between useEffect versus componentDidMount/componentWillUnmount? What are the differences between hooks and this.setState?useEffect 与 componentDidMount/componentWillUnmount 有什么区别? hooks 和 this.setState 有什么区别?
【发布时间】: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>
    );
  }
}

【问题讨论】:

  • 您如何将componentDidMountcomponentWillUnmountsetState 的功能与基于类的组件共享以避免重复?
  • 不知道你的意思,抱歉有点新反应:) 如果你问为什么要作为一个班级来做这件事,这就是为什么我试图弄清楚为什么这个函数不起作用

标签: reactjs rxjs


【解决方案1】:

据我所知,您正在尝试在安装组件时订阅SymbolsObservable,并在卸载组件时取消订阅 RxJS 订阅。

因此,它在 react 钩子中的等价物是使用 empty dependency array 作为 useEffect 钩子:

useEffect(() => {
  let subscription = SymbolsObservable.subscribe(setQuotes);
  return () => subscription.unsubscribe();
}, []);

【讨论】:

  • 我肯定会注意到这一点,但这不是解决方案:(。仍然没有新的报价
  • 实际上,我不应该将 storedQuotes 作为依赖项,因为这是我想要比较的值,如果它正在改变? Doc:如果您使用此优化,请确保数组包含组件范围内的所有值(例如 props 和 state),这些值会随时间变化并被效果器使用。
猜你喜欢
  • 2019-04-12
  • 2016-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-06
  • 1970-01-01
  • 2019-10-07
相关资源
最近更新 更多