在包装组件之前停止反应高阶组件的安装?



我有一个与身份验证相关的 HOC 来包装组件。在包装的组件中,我想要一个由 HOC 设置的用户道具。但是,在子组件中,我在组件DidMount中调用prop,并收到错误:

TypeError: Cannot read property 'identity' of null

这告诉我用户属性(具有身份属性(没有及时设置。 这是 HOC:

export default function withAuth(AuthComponent) {
return class AuthWrapped extends Component {
constructor() {
super();
this.state = {
user: null
};
this.Auth = new AuthService();
}
async componentDidMount() {
try {
const profile = await this.Auth.getProfile(); //Returns a decoded JWT token containing with 'identity':'test'
console.log(profile.identity); //prints 'test' twice
this.setState({
user: profile
});
console.log(this.state.user); //prints the full profile including 'identity':'test' once and null once
}
}
render() {
const user = this.state.user;
console.log(user); //prints null once and the correct profile once
return (
<AuthComponent history={this.props.history} user={this.state.user} />
);
}
};
}

请注意,控制台日志每次打印两次。 这是包装的组件:

class Account extends Component {
componentDidMount() {
axios.get('/user/' + this.props.user.identity).then(res => { //This is the line which triggers the error.
//do something
});
}
render() {
<div><AnotherComponentWrappedBySameHOC/></div>
);
}
}
export default withAuth(Account);

当我删除同样由 withAuth 包装的其他组件时,console.logs 只运行一次。意义。但是,仍打印的日志是打印空的日志。换句话说,错误的日志。

基本上,我认为这意味着使用Auth进行的componentDidMount调用花费的时间太长,并且在Account中的componentDidMount调用之后完成。尽我所能,但是我没有解决方案。有什么想法吗?

你可以等到你有用户,然后渲染孩子像

render() {
const user = this.state.user;
console.log(user); //prints null once and the correct profile once
return (<div>
{user && <AuthComponent history={this.props.history} user={this.state.user} />}
</div>);
}
};

这只会在子组件具有一些数据时呈现user子组件

最新更新