You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

  1. this Binding Problem: You used a regular function as the map callback, which changes the context of this—so this.state will be undefined here. Switch to an arrow function to preserve the component's this context.
  2. Incorrect Condition Check: The second condition checks if item.id is in values, but your requirement specifies checking item.initialVal instead.
  3. Missing Default Return: For items that don't match either condition, you don't return anything, which will result in undefined in your final array. You need to return the original item for these cases.
  4. 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 prevState in setState: When updating state based on previous state, it's best practice to use the functional form of setState to ensure you're working with the most up-to-date state values.
  • Arrow Function in map: Preserves the component's this context so we can access prevState.values correctly.
  • Correct Condition Logic: Checks item.initialVal against prevState.values instead of item.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 undefined entries 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:46:45