React:页面重新加载时数据消失

huangapple go评论72阅读模式
英文:

React: data disappears on page reload

问题

I'm fetching answers from the Nest backend and displaying them. They render fine when I've just made changes to my code but then if I reload the page, they disappear. How can I resolve this?

useEffect(() => {
    fetch("/...")
      .then((response) => response.json())
      .then((data) => setQuestionsData(data))
  }, []);

useEffect(() => {
    setAnswers(questionsData.map((q: { answers: any; }) => q.answers));

    answers.forEach(function (answer: any) {
     const eachAnswer = answer
      eachAnswer.map((a: any) => setAnswer(a.answer))
    });

  }, [questionsData]);

const onChangeCheckbox = (e: React.ChangeEvent<HTMLInputElement>) => {
    let isChecked = e.target.checked;
    setIsChecked(!isChecked)
    isChecked && setAnswerSelected(e.target.value)
  }

return (
<input type="checkbox" value={answer} onChange={(e) => onChangeCheckbox(e)} />{answer}
      <input type="checkbox" value={answer} onChange={(e) => onChangeCheckbox(e)} />{answer}
)
英文:

I'm fetching answers from the Nest backend and displaying them. They render fine when I've just made changes to my code but then if I reload the page, they disappear. How can I resolve this?

useEffect(() =&gt; {
    fetch(&quot;/...&quot;)
      .then((response) =&gt; response.json())
      .then((data) =&gt; setQuestionsData(data))
  }, []);

useEffect(() =&gt; {
    setAnswers(questionsData.map((q: { answers: any; }) =&gt; q.answers));

    answers.forEach(function (answer: any) {
     const eachAnswer = answer
      eachAnswer.map((a: any) =&gt; setAnswer(a.answer))
    });

  }, [questionsData]);

const onChangeCheckbox = (e: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {
    let isChecked = e.target.checked;
    setIsChecked(!isChecked)
    isChecked &amp;&amp; setAnswerSelected(e.target.value)
  }

return (
&lt;input type=&quot;checkbox&quot; value={answer} onChange={(e) =&gt; onChangeCheckbox(e)} /&gt;{answer}
      &lt;input type=&quot;checkbox&quot; value={answer} onChange={(e) =&gt; onChangeCheckbox(e)} /&gt;{answer}
)

答案1

得分: 1

fetch() 是异步的,因此每当页面重新加载时,组件都会重新渲染。当 fetch 函数正在运行时,组件会 没有 数据而渲染,这会导致你的问题。只需使用条件来处理数据已加载的情况,如下所示:

useEffect(() => {
  fetch("/...")
    .then((response) => response.json())
    .then((data) => setQuestionsData(data));
}, []);

useEffect(() => {
  if (questionsData.length > 0) {
    const allAnswers = questionsData.map((q) => q.answers);
    const mergedAnswers = [].concat.apply([], allAnswers);
    setAnswers(mergedAnswers);
  }
}, [questionsData]);

const onChangeCheckbox = (e) => {
  let isChecked = e.target.checked;
  setIsChecked(!isChecked);
  isChecked && setAnswerSelected(e.target.value);
};

return (
  <div>
    {answers.length > 0 ? (
      answers.map((answer) => (
        <div key={answer.id}>
          <input type="checkbox" value={answer.answer} onChange={(e) => onChangeCheckbox(e)} />
          {answer.answer}
        </div>
      ))
    ) : (
      <div>Loading answers...</div>
    )}
  </div>
);

这些更改还将使你的代码运行更快。

英文:

fetch() is asynchronous, and thus, whenever the page reloads, the component re-renders. While the fetch function is running, the component renders without the data, causing your problem. Simply use a condition to handle cases where the data is loaded like so:

useEffect(() =&gt; {
  fetch(&quot;/...&quot;)
    .then((response) =&gt; response.json())
    .then((data) =&gt; setQuestionsData(data));
}, []);

useEffect(() =&gt; {
  if (questionsData.length &gt; 0) {
    const allAnswers = questionsData.map((q: { answers: any }) =&gt; q.answers);
    const mergedAnswers = [].concat.apply([], allAnswers);
    setAnswers(mergedAnswers);
  }
}, [questionsData]);

const onChangeCheckbox = (e: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {
  let isChecked = e.target.checked;
  setIsChecked(!isChecked);
  isChecked &amp;&amp; setAnswerSelected(e.target.value);
};

return (
  &lt;div&gt;
    {answers.length &gt; 0 ? (
      answers.map((answer: any) =&gt; (
        &lt;div key={answer.id}&gt;
          &lt;input type=&quot;checkbox&quot; value={answer.answer} onChange={(e) =&gt; onChangeCheckbox(e)} /&gt;
          {answer.answer}
        &lt;/div&gt;
      ))
    ) : (
      &lt;div&gt;Loading answers...&lt;/div&gt;
    )}
  &lt;/div&gt;
);

These changes will also make your code run faster.

huangapple
  • 本文由 发表于 2023年6月5日 01:12:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76401545.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定