我很反应。
父组件:
// handles parsed json order from child and retrieves parsed data
// child component calls this method by calling this.props.onAdded()
handleAdded = (orderData) => {
let items = orderData.items;
let ids = '';
items.forEach(function(item) {
ids+=item.product_id.toString()+'&';
});
// some async call.
getProducts(ids).then((response) => {
// here is the orderData variable changed based on value got from api...
// lets say that it looks like orderData.item = 'something else'
// changed orderData value like this is printed in child component after file is parsed :(
this.handleFindProductResult(orderData, response.data);
});
}
子组件:
// parse json order from file input
getOrderFromFile = (file) => {
let reader = new FileReader();
reader.readAsText(file);
reader.onload = () => {
const parsed_order = JSON.parse(reader.result); // parsed_order.item = 'something'
console.log('parsed:', parsed_order); // returns parsed_order.item = 'something else'
this.props.onAdded(parsed_order);
};
reader.onerror = (error) => {
this.props.onAdded(false);
};
}
在父组件中,我调用一些setState()
并操纵从子组件获得的值 - parsed_order
。
问题是,console.log('parsed:', parsed_order);
打印更改的值而不是实际解析的值...我无法理解:(
我将不胜感激。
答案 0 :(得分:0)
您正在组件层次结构中的某个位置进一步变异parsed_order
。当对象通过引用传递时,此更新的值将反馈到您尝试注销值的位置。
如果您想在更新之前保留原始值,请务必先将parsed_order
克隆,然后再将其传递给孩子。
为此,请替换:
this.props.onAdded(parsed_order)
与
this.props.onAdded(Object.assign({}, parsed_order))
或构建一些传递的中间变量:
const originalOrder = Object.assign({}, parsed_order);
this.props.onAdded(originalOrder);