最近在开发react项目时,父组件向子组件传值,
例如:向子组件传递的moneyArray 是向服务器请求而来,而且是随时改变的。
<ValutaTable moneyArray={moneyArray} />
如果子组件只是想用第一次的值,这里就需要使用深拷贝的方法来存储第一次的值
子组件代码如下:
constructor (props) {
super(props);
this.state = {
requiredMoney: false,
originMoney: [],
lock: false
};
}
// 获取父组件的传值
componentWillReceiveProps (props) {
// 只取第一次的值,加锁
if (!this.state.lock) {
this.setState({
lock: true,
originMoney: this.deepClone(props.moneyArray)
});
}
}
// 深拷贝方法
deepClone = (o) => {
if (o instanceof Array) {
const n = [];
for (let i = 0; i < o.length; i += 1) {
n[i] = this.deepClone(o[i]);
}
return n;
} else if (o instanceof Object) {
const n = {};
for (const i in o) {
// eslint如果想使用 for-in方法需要先判断对象是否存在
if (Object.prototype.hasOwnProperty.call(o, i)) {
n[i] = this.deepClone(o[i]);
}
}
return n;
}
return o;
};