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用于检查用户是否被授权.
Protected HoC is for checking if user is authorized or not.
问题在于,如果@inject在Protected的外部,则componentDidMount将触发(如果未通过身份验证则触发一次,如果通过身份验证则触发两次).如果我将Protected用作外部装饰器,它似乎可以按预期工作,但会发出警告
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?
推荐答案
在受保护的函数中,我正在通过函数参数Component重新定义React.Component,然后在扩展参数,而不是React.Component. 解决方案->重命名自变量Component->子级
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;
}
这篇关于Mobx Inject,Observer和HoC一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!