React 切换钩子状态

时间:2021-06-26 03:11:09

标签: javascript reactjs react-hooks

我尝试切换单个项目,但不幸的是,每当我尝试切换一个项目时,另一个项目都会受到影响。这是我的代码:

const FAQ = () => {
  const [open, setOpen] = useState(false);
  const [data, setData] = useState(faqData);
  return (
    <FAQSection>
      <FAQTitle>Frequently Asked Questions</FAQTitle>

      <Questions>
        <QuestionItemDetail>
          {data.map((item) => {
            const { id, question, answer } = item;

            return (
              <div key={id}>
                <QuestionItem onClick={() => setOpen(!open)}>
                  <QuestionItemTitle>{question}</QuestionItemTitle>
                  {open ? <Close /> : <Add />}
                </QuestionItem>
                <ReadQuestion>
                  {open && (
                    <ReadQuestionDetail>
                      <ReadQuestionDesc>{answer}</ReadQuestionDesc>
                    </ReadQuestionDetail>
                  )}
                </ReadQuestion>
              </div>
            );
          })}
        </QuestionItemDetail>
      </Questions>
    </FAQSection>
  );
};

这可能有什么问题,因为我确保虚拟数据具有唯一 ID。

2 个答案:

答案 0 :(得分:1)

您的 open 状态用于 data 数组中的所有项目,这就是它在切换时影响所有项目的原因。

我推荐:

  1. 将所有 data 项 html/jsx 放在一个新组件中。
  2. 在这个新组件中,创建一个打开状态,如下所示:
const MyItemComponent = (id, question, answer) => {
  const [open, setOpen] = useState(false);
  return (
    <div key={id}>
      <QuestionItem onClick={() => setOpen(!open)}>
        <QuestionItemTitle>{question}</QuestionItemTitle>
        {open ? <Close /> : <Add />}
      </QuestionItem>
      <ReadQuestion>
        {open && (
          <ReadQuestionDetail>
            <ReadQuestionDesc>{answer}</ReadQuestionDesc>
          </ReadQuestionDetail>
        )}
      </ReadQuestion>
    </div>
  );
}

const FAQ = () => {
  const [data, setData] = useState(faqData);
  return (
    <FAQSection>
      <FAQTitle>Frequently Asked Questions</FAQTitle>

      <Questions>
        <QuestionItemDetail>
          {data.map((item) => {
            const { id, question, answer } = item;

            return (
              <MyItemComponent id={id} question={question} answer={answer} />
            );
          })}
        </QuestionItemDetail>
      </Questions>
    </FAQSection>
  );
};

这将为每个项目提供一个单独的 open 状态。

答案 1 :(得分:0)

因为您使用 boolean 来控制所有打开/关闭。你需要使用 index/id 来控制这个。

const [open, setOpen] = useState(null);
...
onClick={() => setOpen(preOpen => preOpen === id ? null : id)}
...
{open === id && (<ReadQuestionDetail>...</ReadQuestionDetail>)}