我有一个子组件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)}/>
但是,这些功能一直在重新创建。我怎样才能解决这个问题?