[英]Showing Error Cannot read property 'split' of null in microsoft edge, but working fine on chrome
我正在制作一個反應應用程序,
我已將 userName 存儲在 localStorage: userName = Super Admin
在這里,我需要將名字的第一個字母和第二個名字的第一個字母顯示在個人資料部分,例如: SA
所以我先把它分開,然后用 substring 來得到名字的第一個字母。
它在 chrome 上工作正常,但是當我切換到邊緣時,它顯示錯誤:
TypeError: Cannot read property 'split' of null
這是我的代碼:
class TopNavbar extends Component {
state = {};
render() {
var user = localStorage.getItem("userName");
console.log(user) //Super Admin
var components = user.split(" ");
let firstNameLetter = components[0].substring(0, 1);
let secondNameLetter = components[1].substring(0, 1);
console.log(firstNameLetter) //S
console.log(secondNameLetter ) //A
return (
<>
<Nav>
<NavbarContainer>
<NavLogoSection>
<LogoText>FIX-BRIX</LogoText>
</NavLogoSection>
<UserNameSection>
<UserNameText>
{firstNameLetter}
{secondNameLetter}
</UserNameText>
</UserNameSection>
</NavbarContainer>
</Nav>
</>
);
}
}
export default TopNavbar;
注意:
它在谷歌瀏覽器上工作正常,只在微軟邊緣顯示錯誤
任何建議都會有所幫助
你可能在 Microsoft Edge 的本地存儲中還沒有用戶名。 您不能假設 - 您需要在嘗試.split()
之前檢查 userName 是否存在。
考慮:
let firstNameLetter;
let secondNameLetter;
if (user) {
var components = user.split(" ");
firstNameLetter = components[0].substring(0, 1);
secondNameLetter = components[1].substring(0, 1);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.