我有一个组件,我可以在其中进行 API 调用以获取与用户相关的数据。这是我的代码,
class Header extends React.Component {
constructor(props) {
super(props);
this.state = { user: null };
}
componentDidMount() {
getUserData(xobni_api).then((data) =>{
this.setState({user : data});
console.log(this.state.user);//A
});
}
render() {
return (
<div className="header">
<Masthead user={this.state.user.fullName} />//B
<PrimaryNav/>
</div>
);
}
}
export default Header;
在 A
行,我可以呈现用户的详细信息,而在 B
行,用户是 null
,我得到一个错误。我错过了什么。我尝试在 componentDidMount()
和 componentWillMount()
中调用 API。任何帮助表示赞赏。
最佳答案
您的组件第一次呈现 this.state.user
时是 null
,对吗?这就是您在构造函数中设置的内容。因此 this.state.user.fullName
等同于 null.fullName
会崩溃。
您需要让您的初始状态代表您的 user
对象的形状,或者您需要在渲染组件之前进行空检查:
render() {
return (
<div className="header">
{this.state.user && // <-- check if truthy
<Masthead user={this.state.user.fullName} />
}
<PrimaryNav />
</div>
)
}
因为您正在执行 ajax 请求,所以您还可以利用这个机会显示加载指示器:
render() {
return (
<div className="header">
{!this.state.user && // <-- if user is still null
<div>Loading...</div>
}
{this.state.user && // <-- check if truthy
<Masthead user={this.state.user.fullName} />
}
<PrimaryNav />
</div>
)
}
关于javascript - React 中的渲染函数中的状态为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40579715/