【问题标题】:Multiple states in one React component?一个 React 组件中有多个状态?
【发布时间】:2021-04-10 08:20:37
【问题描述】:

我不知道如何在单个 React 组件中使用多个状态,因为我无法在类中调用 useState。

我需要实现的是拥有多个状态并使用 useEffect 独立“监控”它们。

目前我有这样的东西,但据我了解,我不能拥有像 useEffect 这样的东西,仅基于对象字段。我该怎么办?

class ShowPosts extends Component {
  constructor(props) {
    super(props);
    this.state = {
      posts: [],
      sorting:'desc',
      lastPostDate:'none',
      hasMore:false,
      pageNumber:1
    };

  }

【问题讨论】:

  • 你也不能在课堂上使用useEffect
  • @decpk 所以我打算做的唯一方法是将类重写为函数?
  • Hooks 设计用于功能组件。所以你需要重构为functonal 组件或使用componentDidMount 生命周期为sideEffects

标签: javascript reactjs react-hooks


【解决方案1】:
    class ShowPosts extends Component {
      constructor(props) {
        super(props);
        this.state = {
          posts: [],
          sorting:'desc',
          lastPostDate:'none',
          hasMore:false,
          pageNumber:1
        };
    
    componentDidUpdate(prevProps, prevState, snapshot){
      //write the code to monitor this.state and prevState in here
}
    
      }


ComponentDidUpdate is called after every render. This will be same as useEffect for functional components.

【讨论】:

    猜你喜欢
    • 2020-02-24
    • 2017-01-24
    • 1970-01-01
    • 2018-07-17
    • 1970-01-01
    • 2021-02-05
    • 2019-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多