【问题标题】:Dictionary error - TypeError: undefined is not an object字典错误 - TypeError: undefined is not an object
【发布时间】:2020-08-11 07:24:52
【问题描述】:

我正在尝试将一些数据作为字典/JSON 存储在 React-Native 中的 JS 中。

我已经这样定义了字典:

  const [item, setItem] = useState({});
function onUpdate(id, quantity) {
    console.debug('tab index : ' + tabIndex);
    console.debug('id : ' + id);
    console.debug('quantity : ' + quantity);
    console.debug(item);
    item[tabIndex][id] = quantity;
    console.debug(item);
    //I'm not setting it
    //I have even tried declaring a second object, like :
    //let i=item
    //It also causes the same problem
  }

在日志中我得到:

[Tue Aug 11 2020 13:19:13.195]  DEBUG    tab index : 1
[Tue Aug 11 2020 13:19:13.198]  DEBUG    id : 1
[Tue Aug 11 2020 13:19:13.202]  DEBUG    quantity : 1
[Tue Aug 11 2020 13:19:13.203]  DEBUG    {}
[Tue Aug 11 2020 13:19:13.204]  ERROR    TypeError: undefined is not an object (evaluating 'item[tabIndex][id] = quantity')

这是为什么呢?

【问题讨论】:

    标签: javascript json react-native


    【解决方案1】:

    如果item{},那么item[tabIndex]undefined;那么item[tabIndex][id] 等价于undefined[id],这会导致错误。

    【讨论】:

      【解决方案2】:

      正如@Amaden 所提到的,明智的选择, 由于 item[tabIndex] 是 undefined ,因此当您尝试在该 undefined 中添加某些内容时,您会收到错误消息。

      所以你应该先检查未定义的条件,如果是未定义的先创建对象然后添加,否则你可以直接添加数据。

      var item = {};
      var tabIndex = 1;
      var id = 1;;
      
      if(item[tabIndex] === undefined){
      
        item[tabIndex] = {};
        item[tabIndex][id]=10;
      } else {
      
        item[tabIndex][id] = 12;
      }
      
      console.log(item);

      【讨论】:

        【解决方案3】:

        item 对象是空的 {} 这就是为什么你没有定义,请检查你在 items 中设置数据的区域。 先检查未定义的条件,如果未定义先创建对象再添加。

        if(item[tabIndex] === undefined){
            // create object first
        } else {
           // directly add the data
        }
        

        【讨论】:

          猜你喜欢
          • 2016-04-25
          • 2020-08-15
          • 2019-03-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多