Mobx Inject、Observer 和 HoC 结合在一起

2024-04-20

这是我的代码https://jsfiddle.net/v0592ua1/1/ 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 位于 Protected 之外 - componentDidMount 将触发(如果未经过身份验证则触发一次,如果经过身份验证则触发两次)。如果我将 Protected 作为外部装饰器,它似乎按预期工作,但会产生警告

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

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


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

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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Mobx Inject、Observer 和 HoC 结合在一起 的相关文章

随机推荐