我需要将来自props的值推送到状态。
我有一个值,this.props.faculty = 19
,它来自父母。现在,每次我从父母那里得到一个值,我都想把它推到我在孩子身上的状态。所以,最终在我的孩子身上,我会有这样的东西:
this.state.faculties = [19, 20, 13 etc]
我该怎么做?我使用React.js
和TypeScript
。
我试过了:
componentDidUpdate() {
this.setState({ ...this.state, faculties: this.props.faculty, });
}
componentDidUpdate
在每次重新渲染后都会被调用,因为您在其中使用setState而不进行条件检查,这将导致无限循环
您必须检查道具中的前一个和currentValue
是否不同,然后才能推送它。还可以使用函数setState通过添加项目来更新状态
componentDidUpdate(prevProps) {
if (prevProps.faculty !== this.props.faculty) {
// This assumes, faculty cannot contain duplicate values in simultaneous updates
this.setState(prevState=> ({
faculties: prevState.faculties.concat([this.props.faculty])
}));
}
}