Reactjs 从构造函数vs componentDidMount调用props函数?
在我的react组件中,我想在组件呈现时调用props中的一个函数,该函数可以从构造函数或componentDidMount()函数调用。到目前为止,我在react项目中基本上没有看到从构造函数调用函数的情况?但在我的例子中,在哪里调用它并不重要(构造函数vs componentDidMount()。因此,我想在呈现组件之前从构造函数调用它 从构造函数调用函数有什么缺点吗 来自构造函数的调用如下所示:Reactjs 从构造函数vs componentDidMount调用props函数?,reactjs,Reactjs,在我的react组件中,我想在组件呈现时调用props中的一个函数,该函数可以从构造函数或componentDidMount()函数调用。到目前为止,我在react项目中基本上没有看到从构造函数调用函数的情况?但在我的例子中,在哪里调用它并不重要(构造函数vs componentDidMount()。因此,我想在呈现组件之前从构造函数调用它 从构造函数调用函数有什么缺点吗 来自构造函数的调用如下所示: export class XYZ extends Component { construc
export class XYZ extends Component {
constructor(props) {
super(props);
this.state = {
selectedItems: [],
};
this.props.updateId(0);
}
.....
render() {
......
}
}
export class XYZ extends Component {
constructor(props) {
super(props);
this.state = {
selectedItems: [],
};
}
componentDidMount() {
this.props.updateId(0);
}
.....
render() {
......
}
}
来自componentDidMount()的调用如下所示:
export class XYZ extends Component {
constructor(props) {
super(props);
this.state = {
selectedItems: [],
};
this.props.updateId(0);
}
.....
render() {
......
}
}
export class XYZ extends Component {
constructor(props) {
super(props);
this.state = {
selectedItems: [],
};
}
componentDidMount() {
this.props.updateId(0);
}
.....
render() {
......
}
}
编辑:
updateId函数是在父组件中定义的,它只将Id 0传递给父组件,然后父组件将其设置为用于显示内容的状态。如果在呈现子组件之前需要调用父函数
,那么可以在构造函数中调用它,但如果需要调用it在呈现子组件
后,可以使用componentDidMount
方法
请注意,如果您要切换到react钩子,那么有条件地调用父函数或在useEffect
中调用父函数将非常有用。在加载组件后,最好将其放在componentDidMount
中,而不要放在构造函数中。理论上,目前我们看不到任何问题。@PraveenKumarPurushothaman感谢您的回答。为什么建议将其放在componentDidMount中?如果存在需要组件内容的内容怎么办?当两个函数做相同的事情时,使用CDM总是明智的,因为您可以访问加载的元素。