在使用 Redux、flux 和其他发布/订阅方法苦苦挣扎之后,我最终采用了以下技术。我不知道这是否会造成一些大的损害或缺陷,所以把它贴在这里是为了让有经验的程序员了解它的优缺点。
var thisManager = function(){
var _Manager = [];
return{
getThis : function(key){
return _Manager[key];
},
setThis : function(obj){
_Manager[obj.key] = obj.value;
}
}
};
var _thisManager = new thisManager();
// React Component
class Header extends Component{
constructor(){
super();
_thisManager.setThis({ key: "Header", value:this}
}
someFunction(data){
// call this.setState here with new data.
}
render(){
return <div />
}
}
// Then from any other component living far somewhere you can pass the data to the render function and it works out of the box.
i.e.
class Footer extends Component{
_click(e){
let Header = _thisManager.getThis('Header');
Header.somefunction(" Wow some new data from footer event ");
}
render(){
return(
<div>
<button onClick={this._click.bind(this)}> send data to header and call its render </button>
</div>
);
}
}
我在我的应用程序中将 json 作为数据发送,它完美地呈现了所需的组件,我可以在没有任何发布/订阅或深入传递props的情况下调用渲染来调用具有更改 this.setState 的父方法以导致重新渲染.
到目前为止,该应用程序运行良好,我也很喜欢它的简单性。请阐明这种技术的优缺点
问候
编辑:
调用 render 很糟糕,所以我将其更改为另一种方法以获得此设置的更多优缺点。