如何解决从父组件更新道具时未调用React构造函数
我有一个“ ChoiceBox”,我需要一个人字形(向上箭头)旋转180度,但是我一直在尝试更改管理人字形状态的prop的值:
ChoiceBox组件渲染方法
render() {
let animation = this.state.dropActive? "animation-active":"animation-unactive";
return (
<div className="region-choice"
onClick = {()=>{
this.setState({dropActive:!this.state.dropActive});
/*HERE I set the dropmenu and chevron active*/
}}
>
<div className="region-choice__selection ">Filter by Region
/*HERE I SET THE VALUE*/
<Chevron chevronDownDirection={this.state.dropActive} ></Chevron>
</div>
<div ref={this.dropDownOptions} className={"region-choice__options "+ animation} > {/* hidden absolute */}
<div className="options__option option-africa">Africa</div>
<div className="options__option option-africa">America</div>
<div className="options__option option-africa">Asia</div>
<div className="options__option option-africa">Europe</div>
<div className="options__option option-africa">Oceania</div>
</div>
</div>
);
}
然后我将其称为Chevron Tag,这很不错,chevronDownDirection
属性被赋予Chevron构造函数到props
中:
class Chevron extends React.Component{
constructor(props){
super(props);
this.state = {
chevronDownDirection: props.chevronDownDirection,}
}
render(){
let chevronActive = this.state.chevronDownDirection?"chevron--active":"";
return (
<div className={"chevronD " + chevronActive}>
<div className="chevron__left"></div>
<div className="chevron__right"></div>
</div>
);
}
}
当我单击选择框时,dopMenu y Chevron的状态值被反转,并且setState()
内部调用render()
,它将重新呈现Chevron,但是它仅调用render()
方法,不使用构造函数,因此状态值不会被修改,并且state.chevronDownDirection
中的Chevron Component
始终为false。 (我调试了它,单击后断点不会在承包商中停止)。
那么如何改变呢?还是我做错了什么?
解决方法
现在,如果您要更改组件的props,则不会再次调用构造函数,现在,如果您只想使用该值,则可以直接使用props,否则,您可以使用“ static getDerivedStateFromProps()”使用状态
class Chevron extends React.Component{
constructor(props){
super(props);
this.state = {
}
}
render(){
let chevronActive = this.props.chevronDownDirection?"chevron--active":"";
return (
<div className={"chevronD " + chevronActive}>
<div className="chevron__left"></div>
<div className="chevron__right"></div>
</div>
);
}
}
或
class Chevron extends React.Component{
constructor(props){
super(props);
this.state = {
chevronDownDirection: false,}
}
static getDerivedStateFromProps(nextProps,prevState) {
if(nextProps.chevronDownDirection !== prevState.chevronDownDirection){
return {
chevronDownDirection:nextProps.chevronDownDirection
}
}
else return null
}
render(){
let chevronActive = this.state.chevronDownDirection?"chevron--active":"";
return (
<div className={"chevronD " + chevronActive}>
<div className="chevron__left"></div>
<div className="chevron__right"></div>
</div>
);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。