简体   繁体   English

过滤数据后在reactjs中设置状态

[英]setting state in reactjs after filtering the data

I have this data which is coming as props .All items in this array has a date attached to it .I have aa date coming from a function and I want my current state to hold all data for the date I sent in the function . 我有这些数据作为道具。该数组中的所有项目都有一个附加的日期。我有一个来自函数的日期,我希望我的当前状态保存我在函数中发送的日期的所有数据。

I used filter in order to achieve this but it doesn't seem to be working . 我使用过滤器来实现这个目的,但它似乎没用。 Here is the code for the same. 这是相同的代码。

   updateWeather=(date)=>{
    console.log('date is',date);
     this.props.data.map((item)=>{
        console.log('item',item);
     })
    this.setState({

         today: this.props.data.filter( item =>item.date === date({
             date: item.date,
             time:item.time,
             temp: item.temp,
             humidity: item.humidity,
             weather: item.weather[0],
         }))
     });
 }`

This isn't going to work because you're comparing objects. 这将不起作用,因为您正在比较对象。 Variables assigned objects hold references to values in memory. 变量分配的对象保存对内存中值的引用。 So even if the objects look the same, they aren't, unless they're told to point at the same reference like objA = objB which your example isn't doing. 因此,即使对象看起来相同,它们也不会一样,除非被告知要指向您的示例没有做的相同引用(例如objA = objB

You need to adjust your code to compare the individual properties of the objects. 您需要调整代码以比较对象的各个属性。

You might want to grab the Object.keys() of each of the objects your comparing, then create a for loop that compares the values like: 您可能想要获取要比较的每个对象的Object.keys() ,然后创建一个for循环,比较这些值,例如:

const itemKeys = Object.keys(item);
const dateKeys = Object.keys(date);

for(let i = 0, n < itemKeys.length; i < n; i++){
    return item[itemKeys[i]] === date[dateKeys[i]]
}

Something along those lines. 遵循这些原则。

By the way, if your object is not too big, and they don't contain nested objects, so you basically can convert them as string and then compare them, like so 顺便说一句,如果您的对象不是太大,并且它们不包含嵌套对象,则基本上可以将它们转换为字符串,然后进行比较,如下所示

const obj1 = {...};
const obj2 = {...};

JSON.stringify(obj1) === JSON.stringify(obj2);

So basically you are converting both object to be as string, but is you know that your object could have a nested object, so you shouldn't do this, instead iterate the tree object to check that both object has the same vale. 因此,基本上,您要将两个对象都转换为字符串,但是您知道对象可能具有嵌套对象,因此不应执行此操作,而应迭代树对象以检查两个对象是否具有相同的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM