浅比较是当被比较对象的属性使用“===”或严格相等完成时,不会对属性进行更深入的比较。例如
// a simple implementation of the shallowCompare.
// only compares the first level properties and hence shallow.
// state updates(theoretically) if this function returns true.
function shallowCompare(newObj, prevObj){
for (key in newObj){
if(newObj[key] !== prevObj[key]) return true;
}
return false;
}
//
var game_item = {
game: "football",
first_world_cup: "1930",
teams: {
North_America: 1,
South_America: 4,
Europe: 8
}
}
// Case 1:
// if this be the object passed to setState
var updated_game_item1 = {
game: "football",
first_world_cup: "1930",
teams: {
North_America: 1,
South_America: 4,
Europe: 8
}
}
shallowCompare(updated_game_item1, game_item); // true - meaning the state
// will update.
虽然这两个对象看起来相同,但game_item.teams 与updated_game_item.teams 的引用不同。对于两个相同的对象,它们应该指向同一个对象。
因此,这导致被评估的状态被更新
// Case 2:
// if this be the object passed to setState
var updated_game_item2 = {
game: "football",
first_world_cup: "1930",
teams: game_item.teams
}
shallowCompare(updated_game_item2, game_item); // false - meaning the state
// will not update.
这一次每个属性都返回 true 以进行严格比较,因为新旧对象中的 teams 属性指向同一个对象。
// Case 3:
// if this be the object passed to setState
var updated_game_item3 = {
first_world_cup: 1930
}
shallowCompare(updated_game_item3, game_item); // true - will update
updated_game_item3.first_world_cup 属性未通过严格评估,因为 1930 是一个数字,而 game_item.first_world_cup 是一个字符串。如果比较松散(==),这将过去。尽管如此,这也会导致状态更新。
补充说明:
- 进行深度比较毫无意义,因为如果状态对象嵌套较深,则会显着影响性能。但如果它不是太嵌套并且您仍然需要深度比较,请在 shouldComponentUpdate 中实现它并检查是否足够。
- 您绝对可以直接改变状态对象,但组件的状态不会受到影响,因为它在 setState 方法流程中 react 实现了组件更新周期挂钩。如果您直接更新状态对象以故意避免组件生命周期挂钩,那么您可能应该使用简单的变量或对象来存储数据,而不是状态对象。