阻止 React 高阶组件在包装组件之前安装?

Stop React Higher Order Component from mounting before wrapped component?

我有一个与身份验证相关的 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 调用之后完成。尽管尽我所能,但我没有解决办法。有什么想法吗?

你可以等到你有用户然后渲染child like

  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 有一些数据时呈现 child 组件