Reactjs 在渲染方法之外提交道具子对象时触发整个生命周期的反应
在这种情况下,我需要应用程序的组件根据用户单击按钮以两种状态之一呈现。我遇到的问题是,React触发了这些组件的整个生命周期,即使我正在更改的只是组件的状态/道具。我使用的是React 15.6,由于传统的限制(这个应用程序实际上是带有React嵌入式的主干),我也不能使用JSX props.viewMode===“ux”| |“dnd”(基于用户按钮的单击) 以下是相关代码:Reactjs 在渲染方法之外提交道具子对象时触发整个生命周期的反应,reactjs,react-props,react-state,react-lifecycle,Reactjs,React Props,React State,React Lifecycle,在这种情况下,我需要应用程序的组件根据用户单击按钮以两种状态之一呈现。我遇到的问题是,React触发了这些组件的整个生命周期,即使我正在更改的只是组件的状态/道具。我使用的是React 15.6,由于传统的限制(这个应用程序实际上是带有React嵌入式的主干),我也不能使用JSX props.viewMode===“ux”| |“dnd”(基于用户按钮的单击) 以下是相关代码: render() { return this[this.props.viewMode]()
render() {
return this[this.props.viewMode]();
}
ux: function() {
return React.createElement(
"div",
{
"id": this.props.node.type,
"name": this.props.node.component
},
**this.props.children**
);
},
dnd: function() {
return React.createElement(
"div",
{
"id": this.props.node.type,
"name": this.props.node.component
},
return React.createElement(
"div",
{
"id": this.props.node.type,
"name": this.props.node.component
},
**this.props.children**
)
);
},
当运行此代码时,它会在子组件中触发getInitialState()方法,尽管唯一需要更改的是viewMode,它作为道具从链的最高层组件传递到子组件
似乎在render()方法之外对props.children的任何引用都会触发一个完整的生命周期,破坏组件并创建一个新组件
如果我像这样重构代码:
render() {
const children = this.props.children.sort((a, b) => { return a.order > b.order });
const elem = this[this.props.viewMode]();
//assign children to elem, e.g. elem.props.children = children;
return elem;
}
ux: function() {
return React.createElement(
"div",
{
"id": this.props.node.type,
"name": this.props.node.component
},
**null**
);
},
dnd: function() {
return React.createElement(
"div",
{
"id": this.props.node.type,
"name": this.props.node.component
},
return React.createElement(
"div",
{
"id": this.props.node.type,
"name": this.props.node.component
},
**null**
)
);
},
React不会在子对象中触发getInitialState()方法
有人知道为什么会这样吗?我遗漏了什么?经过进一步挖掘,问题似乎与我最初所说的不同。将子元素分配给元素也会触发整个生命周期。是否有任何方法可以格式化它,以便我可以更改组件层次结构顶部的viewMode道具,并在使用子组件时将其向下滚动,而无需销毁和重新创建每个组件。还请注意,我正在使用嵌套JSON结构和子组件的子组件来生成组件,以及一个递归呈现函数,该函数将子对象的子对象传递到嵌套JSON的末尾。