这是我有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将触发(如果不是auth则触发一次,如果经过身份验证则触发两次)。如果我把Protected作为外部装饰器,它似乎按预期工作但产生警告
You are trying to use 'observer' on a component that already has 'inject'
。
处理此问题的正确方法是什么?
答案 0 :(得分:0)
在函数Protected中,我通过函数参数Component重新定义了React.Component,然后我扩展了参数,而不是React.Component。 解决方案 - &gt;重命名参数Component-&gt;孩子们
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;
}