显示错误无法在 Microsoft Edge 中读取 属性 'split' of null,但在 chrome 上工作正常
Showing Error Cannot read property 'split' of null in microsoft edge, but working fine on chrome
我正在制作一个反应应用程序,
我已将用户名存储在本地存储中:userName = Super Admin
这里我需要将名字的第一个字母和第二个名字的第一个字母显示在个人资料部分,例如:SA
所以我首先将其拆分并获取子字符串以获得名称的第一个字母。
它在 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;
注意:
它在 google chrome 上工作正常,仅在 Microsoft Edge 中显示错误
任何建议都会有所帮助
您可能在 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);
}
我正在制作一个反应应用程序,
我已将用户名存储在本地存储中:userName = Super Admin
这里我需要将名字的第一个字母和第二个名字的第一个字母显示在个人资料部分,例如:SA
所以我首先将其拆分并获取子字符串以获得名称的第一个字母。
它在 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;
注意:
它在 google chrome 上工作正常,仅在 Microsoft Edge 中显示错误
任何建议都会有所帮助
您可能在 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);
}