[英]How can I use the filter method on a React component prop?
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.
我已经从父组件传递了月份,当我 console.log(month) 在这种情况下它成功返回 4 。
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. console.log('incomes',incomes) 返回一个空数组。
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:但是,如果我直接在 useEffect 中输入 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)
}
}, [])
Does anyone know how I can properly pass in the month from the parent component into the filter() method?有谁知道我如何正确地将月份从父组件传递到 filter() 方法?
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:
所以我用 parseInt() 把它从一个字符串转换成这样的数字:
const MonthlyIncome = ({incomeData, month}) => {
useEffect(()=>{
console.log(month)
//returns 4
console.log('income data', incomeData)
const m = parseInt(month, 10)
const incomes = incomeData?.filter(i=>{
if(new Date(i?.date).getMonth() === m) {
return i
}})
console.log('incomes', incomes)
}, [])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.