我正在制作一个react-app,
我已经在localStorage:userName = Super Admin
上存储了userName
这里我需要取名字的第一个字母和第二个名字的第一个字母,以显示在个人资料部分,如: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;
注意:
它在google chrome上运行良好,仅在microsoft edge上显示错误
任何建议都会有帮助的
你可能还没有在Microsoft Edge的本地存储中设置userName。你不能假设-你需要检查用户名是否存在之前,试图.split()
它。
考虑:
let firstNameLetter;
let secondNameLetter;
if (user) {
var components = user.split(" ");
firstNameLetter = components[0].substring(0, 1);
secondNameLetter = components[1].substring(0, 1);
}