如何在React组件Prop上使用过滤器方法?
我试图通过阵列过滤,以拔出与特定月份相匹配的所有对象。我已经从母体组件中通过了一个月,当我委托时。Log(月)在这种情况下成功返回4。
这是我组件的开始:
const MonthlyIncome = ({incomeData, month}) => {
useEffect(()=>{
console.log(month)
//returns 4
console.log('income data', incomeData)
if (month) {
const incomes = incomeData?.filter(i=>{
if(new Date(i?.date).getMonth() === month) {
return i
}})
console.log('incomes', incomes)
}
}, [])
console.log('incomes',incomes)返回一个空数组。
但是,如果我直接将4输入到使用效果而不是使用月份,我可以将其成功地将其成功地控制
const MonthlyIncome = ({incomeData, month}) => {
useEffect(()=>{
console.log(month)
//returns 4
console.log('income data', incomeData)
if (month) {
const incomes = incomeData?.filter(i=>{
if(new Date(i?.date).getMonth() === 4) {
return i
}})
console.log('incomes', incomes)
}
}, [])
。 ) 方法?
I'm trying to filter through an array to pull out all the objects that match a specific month. I've passed the month in from the parent component, and when I console.log(month) it successfully returns 4 in this case.
Here's the beginning of my component:
const MonthlyIncome = ({incomeData, month}) => {
useEffect(()=>{
console.log(month)
//returns 4
console.log('income data', incomeData)
if (month) {
const incomes = incomeData?.filter(i=>{
if(new Date(i?.date).getMonth() === month) {
return i
}})
console.log('incomes', incomes)
}
}, [])
The console.log('incomes', incomes) returns an empty array.
However, I can get it to successfully console.log the filtered array if I input a 4 directly into the useEffect instead of using month, like this:
const MonthlyIncome = ({incomeData, month}) => {
useEffect(()=>{
console.log(month)
//returns 4
console.log('income data', incomeData)
if (month) {
const incomes = incomeData?.filter(i=>{
if(new Date(i?.date).getMonth() === 4) {
return i
}})
console.log('incomes', incomes)
}
}, [])
Does anyone know how I can properly pass in the month from the parent component into the filter() method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我找到了一个解决方案,我想实际的问题是来自父母的数字是一个字符串,我需要它是一个实际数字。
因此,我使用parseint()将其从字符串转换为这样的数字:
I found a solution, I guess the actual problem was that the number coming from the parent was a string, and I needed it to be an actual number.
So I used parseInt() to convert it from a string into a number like this: