【发布时间】: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