React中基于匹配计算设置对象数组属性状态的实现问题
Fixing Your React State Update Function
Let's walk through the issues in your current code and fix them to meet your requirements:
Issues in the Original Code
thisBinding Problem: You used a regularfunctionas themapcallback, which changes the context ofthis—sothis.statewill be undefined here. Switch to an arrow function to preserve the component'sthiscontext.- Incorrect Condition Check: The second condition checks if
item.idis invalues, but your requirement specifies checkingitem.initialValinstead. - Missing Default Return: For items that don't match either condition, you don't return anything, which will result in
undefinedin your final array. You need to return the original item for these cases. - Case Mismatch: Your expected result uses lowercase "ok"/"cancel", but your code returns capitalized "Ok"/"Cancel".
Corrected Function Code
setObjState = obj => { this.setState(prevState => { // Use prevState to get the latest state values const finalArr = prevState.arr.map(item => { // First condition: match initialVal with obj.field if (item.initialVal === obj.field) { return { ...item, finalVal: obj.val > 5 ? "ok" : "cancel" }; } // Second condition: initialVal is in values but not matched above else if (prevState.values.includes(item.initialVal)) { return { ...item, finalVal: "" }; } // Default: keep original finalVal else { return item; } }); return { arr: finalArr }; }); };
Key Improvements Explained
- Using
prevStateinsetState: When updating state based on previous state, it's best practice to use the functional form ofsetStateto ensure you're working with the most up-to-date state values. - Arrow Function in
map: Preserves the component'sthiscontext so we can accessprevState.valuescorrectly. - Correct Condition Logic: Checks
item.initialValagainstprevState.valuesinstead ofitem.id, aligning with your requirements. - Full Coverage of Cases: Every item in the array gets a return value—either updated or the original item, so no
undefinedentries in the final array. - Case Consistency: Returns lowercase "ok"/"cancel" to match your expected output.
Testing this function with your sample state and obj will produce exactly the arr structure you're expecting.
内容的提问来源于stack exchange,提问作者joy08
相关产品推荐
相关产品推荐

