我的目標是設定一個變數的初始值,然后直接使用花括號將其放入代碼中。
當我的應用程式呈現時,我在瀏覽器中看到以下錯誤TypeError: Cannot read properties of undefined (reading 'value')。
如果不使用條件陳述句,我還應該怎么做?該行如下:
let dateContent = document.getElementsByClassName('email')[1].value !== undefined ? document.getElementsByClassName('email')[1].value : 'Your date will show up here when you submit it.';
我想解決這個問題,在 try...catch 塊中包裝宣告,以前也是一個函式。但是,將錯誤訊息記錄到控制臺后,讀取值的行將停止作業。我有一個看起來像這樣的組件:
import Name from "../items/Name";
import Contact from "../items/Contact";
import Button from "../items/Button";
import { refresh } from '../libraries/mamaia';
const Mobile = () => {
let dateContent = document.getElementsByClassName('email')[1].value !== undefined ? document.getElementsByClassName('email')[1].value : 'Your date will show up here when you submit it.';
return (
<div className="mobile-container">
<header className="fixed-header" onClick={refresh}><Name /></header>
<main className="mobile-content">
<article className="contact-form-container">
<Contact
firstInput='What is this event?'
secondInput='When does it start?'
secondInputType = 'date'
thirdInput='What additional information do you have?'
/>
<span>
<Button message="Set a Countdown!" />
</span>
</article>
<article className="saved-countdowns">
<h1 className="heading"></h1>
<p className="description"></p>
<p className="description"></p>
<section className="btn-container">
<button className="arrow-btn">
<i className="fas fa-long-arrow-alt-left"></i>
</button>
<button className="arrow-btn">
<i className="fas fa-long-arrow-alt-right"></i>
</button>
</section>
</article>
</main>
</div>
)
}
export default Mobile;
它通過index.js檔案中的路由器呈現:
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import { render } from 'react-snapshot';
import './styles/index.min.css';
import React from 'react';
import reportWebVitals from './reportWebVitals';
import App from './App';
import Mobile from "./comps/Mobile";
render(
<React.StrictMode>
<Router>
<App />
<Switch>
<Route exact path="/app" component={Mobile} />
</Switch>
</Router>
</React.StrictMode>,
document.getElementById('root')
);
reportWebVitals();
我能做些什么來完成這項作業?
uj5u.com熱心網友回復:
錯誤是說那document.getElementsByClassName('email')[1]是undefined,不是document.getElementsByClassName('email')[1].value。所以你應該做
let dateContent = document.getElementsByClassName('email')[1] !== undefined ? document.getElementsByClassName('email')[1].value : 'Your date will show up here when you submit it.';
uj5u.com熱心網友回復:
您可以使用 length 屬性來避免該錯誤,因為您可能會訪問引發此錯誤的陣列中的空槽。
let dateContent = document.getElementsByClassName('email').length > 1 && document.getElementsByClassName('email')[1].value ? document.getElementsByClassName('email')[1].value : 'Your date will show up here when you submit it.';
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/346987.html
標籤:javascript 反应 dom
