var tags = ['tag1', 'tag2', 'tag3', 'tag4', 'tag5',
'tag6', 'tag7', 'tag8', 'tag9', 'tag0'];
var selectedTags = [];
const tagsReducer = (state={}, action) => {
var tagIndex = '';
if(action.type==="ADD_TAG") { //this if statement works as expected
tagIndex = tags.indexOf(action.payload);
selectedTags.push(tags[tagIndex]);
tags.splice(tagIndex, 1);
return {tags, selectedTags};
}
if(action.type==="REMOVE_TAG"){ //this doesn't
tagIndex = selectedTags.indexOf(action.payload);
console.log(selectedTags); //prints the expected array
console.log(action.payload); //prints the expected string
console.log(tagIndex); //prints -1 (doesn't find the string)
console.log(typeof(selectedTags)); //prints object
console.log(typeof(action.payload)); // prints string
tags.push(selectedTags[tagIndex]);
selectedTags.splice(tagIndex, 1);
return {tags, selectedTags};
}
return {tags, selectedTags}
}
字符串对数组项之一进行数学运算,但 indexOf() 函数仍返回 -1。这很令人困惑,因为第一个 Action 工作正常,但第二个 Action 却没有。有什么建议么?
最佳答案
string mathes one of the array items, but the indexOf() function still returns -1
当您调用 indexOf
时,它不匹配数组项之一,因为如果匹配,indexOf
会找到它。 indexOf
isn't broken .
所以剩下两种普遍的可能性:
数组中的字符串看起来应该匹配,但与
payload
中的字符串略有不同。可能不明显的不同方式:- 其中一个(array中的那个或者
payload
中的那个)可以在开头或者结尾有一个空格等。 - 其中一个可能在大小写上略有不同。
- 它们的字符可能略有不同,很容易混淆,例如
ç
和ç
。 - 数组中的条目可能有一个逗号,例如
"thisTag,thatTag"
如果您不匹配"thatTag"
,当然不会去看看,虽然它看起来像"thatTag"
在数组中。 - 其中一个可能是
String
对象,而另一个是字符串基元;String
对象和字符串原语不是===
彼此,indexOf
使用===
测试.
- 其中一个(array中的那个或者
当您调用
indexOf
时,该字符串不在selectedTags
数组中,即使它在控制台中看起来是这样。那是因为 this feature of consoles .
为了解决这个问题,在 indexOf
行设置一个断点,当它被击中时,查看 payload
中的字符串和 selectedTags< 中的字符串
(如果有——如果没有,那就是控制台的问题)。您会发现一些差异。
关于javascript - 为什么 Array.indexOf() 对一个 redux Action 正确工作,但对另一个 Action 却不行? (相同的 reducer ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59114349/