简体   繁体   English

一个 React 组件中有多个状态?

[英]Multiple states in one React component?

I can't figure out how to use multiple states in a single React component, since I can't call useState in a class.我无法弄清楚如何在单个 React 组件中使用多个状态,因为我无法在 class 中调用 useState。

What I need to achieve is to have multiple states and "monitor" them with useEffect independently.我需要实现的是拥有多个状态并使用 useEffect 独立地“监视”它们。

Currently I have something like this, but from what I understand I can't have anything like useEffect based solely on object fields.目前我有这样的东西,但据我了解,我不能有任何像 useEffect 仅基于 object 字段的东西。 How should I go about this?我应该如何 go 关于这个?

class ShowPosts extends Component {
  constructor(props) {
    super(props);
    this.state = {
      posts: [],
      sorting:'desc',
      lastPostDate:'none',
      hasMore:false,
      pageNumber: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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM