【问题标题】:LocalStorage in Next jsNext js 中的 LocalStorage
【发布时间】:2022-01-18 16:44:26
【问题描述】:

我正在尝试将一些项目 set 在 Next js 应用程序中的 localStorage 中,但它无法正常工作,并且我在 localStorage 中没有保存任何内容。

这是我的代码:

function AsyncForm(props) {

const [job, setJob] = useState(
    typeof window !== "undefined"
      ? localStorage.getItem("job")
      : typeof window !== "undefined"
      ? JSON.parse(localStorage.getItem("job"))
      : null
  );

  const [caption, setCaption] = useState(
    typeof window !== "undefined"
      ? localStorage.getItem("caption")
      : typeof window !== "undefined"
      ? JSON.parse(localStorage.getItem("caption"))
      : null
  );

  const [transcription, setTranscription] = useState(
    typeof window !== "undefined"
      ? localStorage.getItem("transcription")
      : typeof window !== "undefined"
      ? JSON.parse(localStorage.getItem("transcription"))
      : null
  );

  useEffect(() => {
    if (!job) return;

    const url = `api/caption/${job.id}`;
    fetch(url)
      .then((res) => res.text())
      .then((caption) => {
        window.localStorage.setItem("caption", JSON.stringify(caption));
        setCaption(caption);
      })
      .catch((err) => console.log(err));
  }, [job]);

  useEffect(() => {
    if (!job) return;

    const transUrl = `/api/transcription/${job.id}/text`;
    fetch(transUrl)
      .then((res) => res.text())
      .then((transcription) => {
        window.localStorage.setItem(
          "transcription",
          JSON.stringify(transcription)
        );
        setTranscription(transcription);
      })
      .catch((err) => console.log(err));
  }, [job]);

return (
    <>
      {job && transcription ? (
        <p style={{ color: "white", paddingTop: "200px" }}>{transcription}</p>
      ) : (
        <p style={{ color: "white", paddingTop: "200px" }}>loading...</p>
      )}

      {job && caption ? (
        <div style={{ color: "white" }}>
          <MediaPlayer src={job.media_url} caption={caption} />
        </div>
      ) : (
        <img alt="hero" src="https://dummyimage.com/300x300" />
      )}
      <div style={{ color: "white" }}>
        <MediaUploader />
      </div>
    </>
  );
}

}

有人知道我在这里做错了什么吗?

【问题讨论】:

  • 您是否检查过您的代码是否在useEffect 块中运行超过if (!job) return;?在您的情况下,useEffect 只有在设置了job 状态时才会运行,但我看不到它最初设置的位置。您的[job, setJob] = useState(...) 块最初将返回null,这意味着您的useEffect 中的代码不会被执行(过去if(!job) return
  • 我想我必须以某种方式通过 getServerSideProps 从/api/job/ 文件中获取job 数据,但不知道如何?

标签: reactjs next.js local-storage use-effect use-state


【解决方案1】:

我认为不需要使用.then((res) =&gt; res.text()),因为你想转换为json,你可以把它放在标题content-type : application/json 中,然后在函数中放置console.log(),如果没有数据,则显示结果检查 insomnia 或 postman 中的 api 以检查您是否得到任何结果

【讨论】:

    【解决方案2】:

    Next Js 使用的是不与浏览器通信的节点服务器。

    我建议使用库 nookies 将数据保存在 cookie 中并获取数据。

    https://npm.io/package/nookies

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      • 2019-02-07
      • 2021-12-12
      • 1970-01-01
      • 2018-11-18
      • 2019-02-05
      • 2021-03-31
      相关资源
      最近更新 更多