[英]Comparing two state arrays in react will not return a boolean (True) if they are equal
當我比較我的 state 中的兩個 arrays 時,如果它們相等,我想將第三個 state Z84E2C5“C64F38FA28BA73”更改為“C64F38FA28BA73” 但是,當兩個 arrays 相等時,我為檢測它而創建的 if 語句不會返回“true”。
我在 setInterval() 中執行此操作,我不知道這是否與此問題有關...
class DisplaySort extends Component {
constructor(props) {
super(props);
this.state = {
array: [1, 2, 3],
array2: [1, 2, 3],
istrue: false,
};
this.compare = this.compare.bind(this);
};
render() {
return (
<div>
<button onClick={this.compare}>Compare</button>
</div>
);
}
compare(e) {
this.myInterval = setInterval(() => {
let a = this.state.array.slice();
let b = this.state.array2.slice();
if (a === b) {
this.setState({ istrue: true });
clearInterval(this.myInterval);
}
(設置的時間間隔被用於應用程序中的另一個操作(也就是在 if 之后有一個 else 語句),但為簡潔起見被排除在外)
如果你這樣比較 arrays ,你總是會得到錯誤的,除非你檢查a === a
這是一個 function 來檢查對象/數組之間的相等性,如果嵌套也是如此:
function isEqual(value, other) {
// Get the value type
var type = Object.prototype.toString.call(value);
// If the two objects are not the same type, return false
if (type !== Object.prototype.toString.call(other)) {
return false;
}
// If items are not an object or array, return false
if (['[object Array]', '[object Object]'].indexOf(type) < 0) {
return false;
}
// Compare the length of the length of the two items
var valueLen = type === '[object Array]' ? value.length : Object.keys(value).length;
var otherLen = type === '[object Array]' ? other.length : Object.keys(other).length;
if (valueLen !== otherLen) {
return false;
}
// Compare two items
var compare = function (item1, item2) {
// Get the object type
var itemType = Object.prototype.toString.call(item1);
// If an object or array, compare recursively
if (['[object Array]', '[object Object]'].indexOf(itemType) >= 0) {
if (!isEqual(item1, item2)) {
return false;
}
}
// Otherwise, do a simple comparison
else {
// If the two items are not the same type, return false
if (itemType !== Object.prototype.toString.call(item2)) return false;
// Else if it's a function, convert to a string and compare
// Otherwise, just compare
if (itemType === '[object Function]') {
if (item1.toString() !== item2.toString()) return false;
} else {
if (item1 !== item2) return false;
}
}
};
// Compare properties
if (type === '[object Array]') {
for (var i = 0; i < valueLen; i++) {
if (compare(value[i], other[i]) === false) return false;
}
} else {
for (var key in value) {
if (value.hasOwnProperty(key)) {
if (compare(value[key], other[key]) === false) return false;
}
}
}
// If nothing failed, return true
return true;
}
這不是我寫的,我很久以前google了。
你可以簡單地使用這個:
if(JSON.stringify(a) == JSON.stringify(b)){YOUR CODE HERE};
注意:此解決方案適用於您的用例,但不適用於復雜的數組值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.