Mobx Inject、Observer 和 HoC 一起

Mobx Inject, Observer and HoC together

这是我有的代码 https://jsfiddle.net/v0592ua1/1/

const {observable, computed, extendObservable} = mobx;
const {observer,  inject, Provider} = mobxReact;
const {Component} = React;
const {render} = ReactDOM
class AppState {
    @observable authenticated = false;
    @observable authenticating = false;
}

class Store2 {
    @observable blah = false;
}

function Protected(Component) {
    @inject("appState")
    @observer
    class AuthenticatedComponent extends Component {
        render() {
            const { authenticated, authenticating } = this.props.appState;
            return (
                <div className="authComponent">
                    {authenticated
                        ? <Component {...this.props} />
                        : !authenticating && !authenticated
                                ? <p> redirect</p>
                                : null}
                </div>
            );
        }
    }
    return AuthenticatedComponent;
}


@inject("s2")
@Protected
@observer
class Comp extends Component {
  componentDidMount() {
        console.log('mount');
  }

    render() {
        return (
            <p>blabla</p>
        )
    }
}

const appS = new AppState();
const s2 = new Store2();

render(
    <Provider appState={appS} s2={s2}>
        <Comp  />
    </Provider>,
    document.getElementById("app")
)

受保护的HoC用于检查用户是否被授权。

问题是,如果@inject 在受保护的外部 - componentDidMount 将触发(如果未验证则触发一次,如果已验证则触发两次)。如果我将 Protected 作为外部装饰器,它似乎可以按预期工作但会产生警告

You are trying to use 'observer' on a component that already has 'inject'

处理这个问题的正确方法是什么?

在 Protected 函数中,我通过函数参数 Component 重新定义了 React.Component,然后我扩展了参数,而不是 React.Component。 解决方案 -> 重命名参数 Component -> Children

function Protected(Children) {
    @inject("appState")
    @observer
    class AuthenticatedComponent extends Component {
        render() {
            const { authenticated, authenticating } = this.props.appState;
            return (
                <div className="authComponent">
                    {authenticated
                        ? <Children {...this.props} />
                        : !authenticating && !authenticated
                                ? <p> redirect</p>
                                : null}
                </div>
            );
        }
    }
    return AuthenticatedComponent;
}