【发布时间】:2018-06-02 19:42:58
【问题描述】:
我有一个与身份验证相关的 HOC,它封装了组件。在包装的组件中,我想要一个由 HOC 设置的用户道具。但是,在一个子组件中,我调用了 componentDidMount 中的 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} />
);
}
};
}
请注意,console.logs 每次打印两次。 这是包装好的组件:
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 只运行一次。说得通。但是,仍然打印的日志是打印空的日志。换句话说,错误的日志。
基本上,我认为这意味着 withAuth 中的 componentDidMount 调用花费了太长时间,并且在 Account 中的 componentDidMount 调用之后完成。尽我所能,但我没有解决办法。有什么想法吗?
【问题讨论】:
标签: javascript reactjs higher-order-components