[英]React component rerenders when sending function as props to it
我有一个子组件StartExam
,我从父组件发送两个函数作为道具。 我看到它不断重新渲染,因为它一直在获取新的函数值。 我已经使用这段代码找出正在更新哪些道具,它给了我发送的两个函数。
componentDidUpdate(prevProps, prevState, snapshot) {
Object.entries(this.props).forEach(([key, val]) =>
prevProps[key] !== val && console.log(`Prop '${key}' changed`)
);
if (this.state) {
Object.entries(this.state).forEach(([key, val]) =>
prevState[key] !== val && console.log(`State '${key}' changed`)
);
}
}
这就是我从父组件发送函数的方式:
<Route path={`${matchedPath}/start`}
render={
this.examStatusGuard(
'NOT_STARTED',
(props) =>
<StartExam
language={this.state.language}
startExam={() => this.startExam()}
logAction={(action) => this.logAction({action})}/>)
}
/>
这是examStatusGuard
函数:
examStatusGuard(requiredState, renderFunc) {
return (props) => {
if (this.state.exam.status !== requiredState) {
return <Redirect to={this.examStatusDefaultUrl()}/>
}
return renderFunc(props);
}
}
这是我作为道具发送的两个函数:
logAction(actionModel) {
const wholeActionModel = {
language: this.state.language,
taskId: null,
answerId: null,
...actionModel
};
console.log(wholeActionModel);
return wholeActionModel;
}
startExam() {
this.logAction({action: actions.EXAM_STARTET});
this.examGateway.startExam()
.then(() => this.loadExam())
.then(() => {
this.props.history.push("/exam/task/0");
this.logAction({action: actions.TASK_OPEN, taskId: this.state.exam.tasks[0].id});
});
};
我不希望重新创建这些函数的原因是在子组件中我有一个调用logAction
的方法,并且它一直被调用,而不仅仅是一次。 这是方法:
renderFirstPage() {
this.props.logAction(actions.INFOSIDE_OPEN);
return <FirstPage examInfo={this.props.eksamensInfo}>
{this.gotoNextPageComponent()}
</FirstPage>
}
我试图与发送功能,如它在答复建议,但结合this
对他们说:
<StartExam
language={this.state.language}
startExam={this.startExam.bind(this)}
logAction={this.logAction.bind(this)}/>
但是,这些功能一直在重新创建。 我怎样才能解决这个问题?
当您像这样发送函数时,您正在创建一个匿名函数,每次父组件渲染时都会重新创建该函数:
startExam={() => this.startExam()}
这是一个匿名函数,它在生活中的全部目的是调用实际的函数startExam
。 它是在父级的渲染函数中定义的,因此每次都会重新创建。 您也可以直接发送该功能,即
startExam={this.startExam}
在这种情况下,道具现在引用一个稳定的函数,不会每次都重新创建。 我想这会解决你的问题。
但是,我并不完全清楚为什么每次都重新创建该函数并且您的子组件正在重新渲染很重要。 道具不会在无限长的时间内改变,而只会在父级重新渲染时改变。 这通常不是问题,除非您基于其他一些操作来查看之前的 props 是否已更改(例如 lodash, _.isEqual(prevProps,this.props)
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.