我想改变道具的一些内部属性。Props声称是不可变的,但当我更改该值时,父对象的状态值正在发生变化。我读到props是不可变的。但改变价值反映在父母身上。
class ParentComp extends React.Component {
constructor(props) {
super(props);
let property = {someProperty:'ABCD'};
this.state={
myState: property
}
}
render() {
return(
<div>
Parent:{JSON.stringify(this.state.myState)}
<ChildComp pState={this.state.myState} />
</div>
);
}
}
class ChildComp extends React.Component {
render() {
this.props.pState.someProperty = '1234';
return(
<div>
Child:{JSON.stringify(this.props.pState)}
</div>
);
}
}最后,我看到两个值都更改为1234。在在线小提琴中,它按预期工作(即,父值不变)。但在我的项目中,父对象正在更改。
我如何实现这个用例,在这个用例中,我想要更改props中的一些属性,而不是反映在父对象的状态中?
发布于 2018-05-25 22:21:30
我读到道具是不变的
这不是真的-你只应该把它们当做是不可变的。换句话说,它们只是普通的javascript对象,你不应该改变它们。
发布于 2018-05-25 22:25:28
如果你想改变道具的值,你应该首先在状态中转储道具,然后在该状态上进行变异。
改变道具不是最佳实践。所以你的ChildComp应该是这样的:
class ChildComp extends React.Component {
constructor(props) {
super(props);
this.state = {
pState: props.pState,
}
}
componentDidMount() {
const { pState } = this.state.
pState.someProperty = '1234';
this.setState({
pState,
});
}
render() {
return(
<div>
Child:{JSON.stringify(this.state.pState)}
</div>
);
}
}https://stackoverflow.com/questions/50531271
复制相似问题