【发布时间】:2021-01-17 03:53:32
【问题描述】:
在 App.js 中
<Router>
<Confirmation path="/confirmation/:token" />
</Router>
在 Confirmation.js 中
function Confirmation(props) {
const verificationMessage = document.getElementById("verification-message");
const token = props.token;
// console.log(token);
fetch(`/api/confirmation/${token}`)
.then((res) => res.json())
.then((data) => {
// console.log(data.status);
if (data.status === "alreadyVerified") {
verificationMessage.innerHTML = "You have already been verified!";
} else {
console.log("already verified");
}
});
return (
<div className="confirmation">
<h5>
<span id="verification-message">You have been successfully verified!</span> Please navigate
back to{" "}
<Link to="/login" style={link_style}>
<span className="confirmation__toLogin">login page</span>
</Link>{" "}
to sign on!
</h5>
</div>
);
}
即使已经定义了verificationMessage,但在尝试将消息插入HTML时,它的值为null。
错误信息: Uncaught (in promise) TypeError: Cannot set property 'innerHTML' of null
我该如何解决这个问题?
【问题讨论】:
-
你不应该在 React 中手动改变 DOM。相反,您可以将 fetch 调用移至
useEffect并使用useState设置所需的值(或使用类组件以老式方式进行),然后将所需的数据传递给 JSX。
标签: javascript html reactjs