Mobx Inject, Observer and HoC together

大兔子大兔子 提交于 2020-01-03 02:19:25

问题


Here a code that i have 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")
)

Protected HoC is for checking if user is authorized or not.

The problem is that if @inject is outer of Protected - componentDidMount will trigger (once if not auth, and twice if authenticated). And if i put Protected as outside decorator it seems to work as expected but produce a warning

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

What is a proper way to handle this?


回答1:


In function Protected i was redefining React.Component by function argument Component, then i was extending argument, not React.Component. Solution -> rename argument 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;
}


来源:https://stackoverflow.com/questions/44906823/mobx-inject-observer-and-hoc-together

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!