自定义过滤功能未按预期工作,请求技术排查协助
Hey there! Let’s break down why your custom filter might not be behaving as expected, based on the code snippet you shared. I’ve spotted a few common pitfalls and fixes to get it working right:
Potential Issues & Fixes
Uninitialized
entitieshandling
Ifthis.entitiesisundefinedornullinitially, assigning it toarraywill cause aCannot read property 'filter' of undefinederror. Always add a fallback to an empty array:let array = this.entities || [];Empty filter values are not skipped
If a filter key has an empty string value (after trimming), your current logic will still run the filter—butincludes('')returnstruefor every string. This means empty filters won’t narrow results at all, which might not be what you want. Add a check to skip empty filter conditions:Object.keys(filter).forEach(key => { const filterString = filter[key].trim().toLowerCase(); if (!filterString) return; // Skip empty filter values // Rest of your filtering logic });Debugging
propertyAccessorreliability
Ifthis.propertyAccessorisn’t correctly retrieving the entity’s property value, your filter will never work as intended. Add a quick debug log to verify the values being compared:const propertyValue = this.propertyAccessor(entity, key); const propertyString = (propertyValue || '').toString().trim().toLowerCase(); console.log(`Comparing ${key}: entity value = "${propertyString}", filter value = "${filterString}"`);MobX
createTransformerdependency tracking
Since you’re usingcreateTransformer(from MobX), make surethis.entitiesis an observable array. If it’s a plain array, the transformer won’t re-run when the data changes, leading to stale results.
Revised Code Example
Here’s a polished version of your function incorporating these fixes:
public filtered = createTransformer((filter: { [key: string]: string }): EntityType[] => { let array = this.entities || []; // Fallback to empty array Object.keys(filter).forEach(key => { const filterString = filter[key].trim().toLowerCase(); if (!filterString) return; // Skip empty filters array = array.filter(entity => { const propertyValue = this.propertyAccessor(entity, key); const propertyString = (propertyValue || '').toString().trim().toLowerCase(); return propertyString.includes(filterString); }); }); return array; });
Debugging Tips
- Log the initial
arrayvalue before filtering to confirm you’re starting with the correct dataset. - Check the
filterobject to ensure it’s receiving the key-value pairs you expect (e.g., no typos in property names). - Test with a single filter key first to isolate whether the issue is with multi-property logic or a specific property’s handling.
内容的提问来源于stack exchange,提问作者Kamil Łapiński

