停止在包装组件之前安装高级订单组件?

时间:2018-06-02 19:42:59

标签: javascript reactjs higher-order-components

我有一个与auth相关的HOC包装组件。在包装的组件中,我想要一个由HOC设置的用户道具。但是,在子组件中,我在componentDidMount中调用prop,我得到错误:

TypeError: Cannot read property 'identity' of null

这告诉我用户prop(具有identity属性)没有及时设置。 这是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只运行一次。说得通。但是,仍然打印的日志是打印为null的日志。换句话说,错误的日志。

基本上,我认为这意味着withAuth中的componentDidMount调用时间太长,并且在Account中调用componentDidMount后完成。尽管我可能会尝试,但我没有解决方案。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您可以等待,直到您拥有该用户,然后将该子项渲染为

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

相关问题