[英]Javascript find() array method is returning undefined. what am I doing wrong?
On the click of a button.单击一个按钮。 I am dispatching the id to my resellerSlice so that I can be able to use.find() and select the exact array object that has the same id as my id我正在将 id 发送到我的 resellerSlice,这样我就可以使用 .find() 和 select 与我的 id 具有相同 id 的确切数组 object
const handleDetailsModal = (e) => {
setResellersId(e.currentTarget.id)
dispatch(uiAction.toggle())
dispatch(
toggleResellers (resellersId)
)
}
On getting to the resellerSlice关于 resellerSlice
const resellerSlice = createSlice({
name: 'reseller',
initialState,
reducers: {
toggleResellers(state, action) {
const resellerId = action.payload;
const clickedReseller = state.resellers?.find((reseller) => reseller.id === resellerId);
console.log(clickedReseller) //returns undefined(this is the problem)
}
}
})
What am I doing wrong?我究竟做错了什么?
I need the const 'clickedReseller' to contain the properties of object that its Id is the same as the 'resellersId', So I can use the object.我需要 const 'clickedReseller' 来包含 object 的属性,它的 ID 与 'resellersId' 相同,所以我可以使用 object。
Here's my initial state这是我最初的 state
const initialState = [
{
resellerName: 'xxxx xxxx',
id: 1,
resellerLimits: [
{
USD: 700,
GBP: 200,
EURO: 990,
}
],
paymentMethods: [
'wirePay',
'flux',
'bankTransfer'
],
totalTransactions: 0,
rating: 0,
},
This is what the objects inside the array looks like这就是数组中的对象的样子
So, I finally figured it out.所以,我终于想通了。
My resellerId was actually a string and not an integer.我的 resellerId 实际上是一个字符串,而不是 integer。
I discovered this after doing a typeOf() on it.我在对它做了 typeOf() 之后发现了这一点。
So instead of using the === comparison operator I used == and it worked out.因此,我没有使用 === 比较运算符,而是使用了 == 并且成功了。
Thanks guys多谢你们
Normally, the state of your reducer is alreay the state.resellers
as demonstrated in the redux toolkit documentation , so you can do directly state.find(reseller => reseller.id === resellerId)
!通常情况下,你的reducer的state.resellers
是redux工具包文档中展示的state.resellers ,所以你可以直接做state.find(reseller => reseller.id === resellerId)
!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.