【问题标题】:Display array elements with next and prev button using ReactJS使用 ReactJS 显示带有下一个和上一个按钮的数组元素
【发布时间】:2022-11-02 15:53:37
【问题描述】:

我有一个包含 10 个对象的数组,称为 emailThreads

我正在尝试使用下一个和上一个按钮显示这些对象,但它没有按预期工作。

      <Controls>
        <Button onClick={previousEmail}>Previous Email</Button>
        <SubjectDetails>
          <Subject>SUBJECT</Subject>
          <SubjectTitle>{emailThreads[emailIndex].subject}</SubjectTitle>
          <SentAtDetails>Sent At {emailThreads[emailIndex].deliveredAt}</SentAtDetails>
        </SubjectDetails>
        <Button onClick={nextEmail}>Next Email</Button>
      </Controls>

这是previousEmailnextEmail 的代码

  const [emailIndex, setEmailIndex] = useState(0);
  const previousEmail = () => {
    setEmailIndex((prevIndex) => {
      prevIndex !== 0 ? prevIndex - 1 : prevIndex;
    });
  };
  const nextEmail = () => {
    setEmailIndex((prevIndex) => {
      prevIndex !== emailThreads.length ? prevIndex + 1 : prevIndex;
    });
  };

当我点击下一封电子邮件时,

TypeError: Cannot read properties of undefined (reading 'subject')

任何帮助都会很棒,谢谢

【问题讨论】:

  • 为什么你想要 prevIndex 从 prevIndex 被传递的地方?

标签: reactjs


【解决方案1】:

你可以简单地做到这一点。

const previousEmail = () => {
    setEmailIndex(
      emailIndex !== 0 ? emailIndex - 1 : emailIndex;
    );
  };
  const nextEmail = () => {
    setEmailIndex(
      emailIndex !== emailThreads.length ? emailIndex + 1 : emailIndex;
    );
  };

【讨论】:

    【解决方案2】:

    似乎您没有在 setemailindex 回调中返回任何内容,因此将您的代码更改为

     setEmailIndex((prevIndex) => prevIndex !== emailThreads.length ? prevIndex + 1 : prevIndex);
    

    或者

    setEmailIndex((prevIndex) => {
        retrun  prevIndex !== emailThreads.length ? prevIndex + 1 : prevIndex;
        });
    

    应该管用

    【讨论】:

      【解决方案3】:

      请小心,因为您正在与length 进行比较,而不是&lt;= length - 2(或&lt; length - 1),因此在当前索引中添加+ 1 将在某些时候导致异常。

      使用这样的东西

      const nextEmail = () => {
          setEmailIndex(prevIndex => prevIndex < emailThreads.length - 1 ? prevIndex + 1 : prevIndex);
      }
      

      【讨论】:

        猜你喜欢
        • 2016-05-21
        • 2019-04-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多