[英]How to prevent one of the state variables of a child page from changing its value?How to retain initial value as props from the parent page? - ReactJS
My child page opens when a flag in my parent called 'isChildOpen' is true. 当父级中名为“ isChildOpen”的标志为true时,将打开子页。 Now I want to make the state variable filtered2 in my child unchangable. 现在,我想使我的孩子中的状态变量filter2不可更改。 filtered and filtered2 should get same value from the parent when I open the child page but while filtered can change during any operation in the child, filtered2 should retain its initial value of the opening of child every time. 当我打开子页面时,filtered和filtered2应该从父项获得相同的值,但是尽管filterd可以在子项中的任何操作期间更改,但filterd2每次都应保留其打开子项的初始值。 It should get its value from the parent when the parent is opened but not change due to any operations in the child. 当打开父级时,它应该从父级获取其值,但由于子级中的任何操作而不能更改。
Child Code 子代码
class Child extends Component {
constructor(props) {
super(props);
this.state = {
data: this.props.data,
filtered: this.props.filtered
filtered2: this.props.filtered
};
}
I have tried Object.freeze but is of no help. 我尝试了Object.freeze,但没有帮助。
This is how the child opens from the parent page 这是孩子从父页面打开的方式
{this.state.isChildOpen &&
<Child
data={this.state.data}
filtered={this.state.filtered}
/>}
Can anyone help me in this regard? 有人可以在这方面帮助我吗? filtered can change during any operations in the child but filtered2 should retain the initial value after the child is just opened. 在子级中的任何操作期间,filterd均可更改,但在刚刚打开子级后,filterd2应保留初始值。
I believe you could use this.props.filtered.slice()
我相信你可以使用this.props.filtered.slice()
This would make a replica of the value 这将复制该值
{this.state.isChildOpen &&
<Child
data={this.state.data}
filtered={this.state.filtered}
filtered2={this.state.filtered2}
/>}
when this.state.isChildOpen
switch to false and then again to true a new instance of Child
is created and so the constructor is again invoked with a new value of filtered2
. 当this.state.isChildOpen
开关为false,然后再真正的新实例Child
创建等构造再次与新值调用filtered2
。
you should pass isChildOpen
as a prop down to Child
and handle the rendering from there 您应该将isChildOpen
作为道具传递给Child
并从那里处理渲染
<Child
data={this.state.data}
filtered={this.state.filtered}
filtered2={this.state.filtered2}
isChildOpen={this.state.isChildOpen}
/>}
class Child extends Component {
constructor(props) {
super(props);
this.state = {
filtered2: this.props.filtered2
};
}
render() {
const { data, filtered, isChildOpen } = this.props; // this props will update following the parent
const { filtered2 } = this.state; //this prop will be controlled by the child and will keep the value once the instantiation
if(!isChildOpen) {
return null;
}
// otherwise render the component
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.