【问题标题】:ReactJS TypeError: Cannot set property 'innerHTML' of null even though it's been definedReactJS TypeError:即使已定义,也无法将属性“innerHTML”设置为null
【发布时间】: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


【解决方案1】:
Why need to set innerHTML .
   

    const {useState, useEffect} = React; 
       function Confirmation(props) {
          const [verificationMessage, setVerificationMessage] = useState(""); 
          const token = props.token;
          // console.log(token);
        
        useEffect(() => {

             fetch(`/api/confirmation/${token}`)
                .then((res) => res.json())
                .then((data) => {
                  // console.log(data.status);
                  if (data.status === "alreadyVerified") {
                    setVerificationMessage("You have already been verified!");
                  } else {
                    console.log("already verified");
                  }
                });
    
    
    }, [])
          
        
          return (
            <div className="confirmation">
              <h5>
                <span id="verification-message">{verificationMessage}</span> Please navigate
                back to{" "}
                <Link to="/login" style={link_style}>
                  <span className="confirmation__toLogin">login page</span>
                </Link>{" "}
                to sign on!
              </h5>
            </div>
          );
        }

【讨论】:

  • 非常感谢!我目前还很陌生,这对我很有帮助。
猜你喜欢
  • 2021-05-23
  • 2023-04-09
  • 2020-12-19
  • 2014-08-20
  • 1970-01-01
  • 1970-01-01
  • 2014-08-25
  • 2013-08-16
  • 2017-04-26
相关资源
最近更新 更多