【发布时间】:2016-06-09 13:05:46
【问题描述】:
在与 Redux、flux 和其他 pub/sub 方法苦苦挣扎之后,我最终采用了以下技术。我不知道这是否会造成一些大的损害或缺陷,所以把它贴在这里让有经验的程序员了解它的优缺点。
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 作为数据发送,它完美地渲染了所需的组件,我可以在没有任何 pub/sub 或深度传递道具的情况下调用渲染来调用父方法,并更改 this.setState 以导致重新渲染。
到目前为止,该应用程序运行良好,我也喜欢它的简单性。请阐明这种技术的利弊
问候
编辑:
调用 render 很糟糕,因此我将其更改为另一种方法,以获得此设置的更多优点和缺点。
【问题讨论】:
-
虽然这适用于非常有限的用例,如您提供的示例,但它会干扰反应组件的生命周期。 render 方法永远不会被直接调用,也不应该有输入,这使得它不纯。至少,公开一个不同的公共方法,它接受你发送来渲染的任何东西。在该方法中执行 setState ,它将隐式调用渲染。最后而不是渲染调用该方法。
-
谢谢@HazardouS,当然是对的,但是技术呢,基本上我没有公开它是可以调用渲染的参考,我猜 setState 会做同样的效果加上破坏性部分将数据作为参数发送到渲染函数?
-
SO 应用程序不太适合长解释 :)。请阅读 React 中的纯渲染方法假设。还有 React 批量渲染,这就是为什么不应该直接调用它的原因。
标签: javascript reactjs