簡體   English   中英

無法將項目添加到 JS 地圖

[英]Cannot add item to JS Map

我只是想在 Javascript 中將一個項目添加到地圖(如字典)中。 我正在使用 React Native。

import React, { Component } from 'react';

import {
  AppRegistry,
  View,
  Button,
} from 'react-native';

export class Stack extends Component {
  constructor(props){
    super(props)
    this.state = {
      statelist: new Map(),
    }
  }

  add_func_list() {
    let plist = new Map()
    plist.set(1, 'ddd');
    alert(JSON.stringify(plist))   
  }

  add_state_list(){
    let statelist = this.state.statelist
    statelist.set(2, 'ggg');
    this.setState({statelist})
  }

  render() {
      return (
          <View>
              <Button title="add to func list" onPress={this.add_func_list} />
              <Button title="add to state list" onPress={this.add_state_list} />
          </View>
      );
  }
}

export default function App(props) {
  return (
      <Stack />
  );
};

AppRegistry.registerComponent('default', () => App);

如果您按下第一個按鈕,我將添加到函數中的局部變量。 沒有添加任何內容,警報顯示 {}

第二個按鈕應該添加到狀態變量,但我收到一個錯誤:“TypeError: undefined is not an object (evaluating 'this.state.statelist')

有任何想法嗎?

第二個錯誤是由於代碼錯誤:

onPress={this.add_state_list.bind(this)}

或將方法轉換為箭頭函數。

關於警報,您無法對其進行字符串化。 它的數據是原型。 Map 是一個可迭代的。 你可以做 :

alert(plist.size);
or
alert(plist.get('2'));
  add_func_list() {
    let plist = new Map()
    plist.set(1, 'ddd');
    alert(JSON.stringify(plist.get(1))   
  }

感謝穆克什和維維克。 我是 RN 的新手,所以我不知道打印地圖的限制。 我的構造函數中實際上綁定了該方法,但未能將其復制到示例中。 不幸的是,結果是它產生了與我在真實系統中相同的錯誤,我被愚弄了。 不管怎樣,你在我發布的時候回答了問題,我很感激。 結果證明真正的問題是繼承的結果,正如我現在正在學習的那樣,狀態繼承不像其他繼承那樣工作。

import React, { Component } from 'react';

import {
  AppRegistry,
  Button,
  View,
} from 'react-native';


export class Stack extends Component {
  constructor(props){
    super(props)
    this.state = {
      statelist: new Map(),  // get's overwritten and destroyed by child state assgnment
    }
    //this.statelist = new Map(),  <-- this way it works fine if child sets state
    this.add_state_list = this.add_state_list.bind(this)
  }

  add_state_list(){
    this.statelist.set(2, 'ggg');
    alert(JSON.stringify(this.statelist.get(2)))   
  }
}


export class StackHandler extends Stack {
  constructor(props){
    super(props)
    // if I remove this.state assignment below, it works
    this.state = {
      count:0  // destroys parent's state
    };
  }

  render() {
      return (
          <View>
              <Button title="add to state list" onPress={this.add_state_list} />
          </View>
      );      
  }
}

export default function App(props) {
  return (
     <StackHandler/>
  );
};

AppRegistry.registerComponent('default', () => App);

這段代碼更符合我的問題。 StackHandler 類和 Stack 類都有狀態變量。 Stackhandler 繼承了 Stack。 當 Stackhandler 設置其狀態變量時,它會破壞其父級的狀態。 對於我們有 OOP 背景的人來說,這似乎違反直覺。 無論哪種方式,我現在都知道不要這樣做並且可以解決它。 如果有人有一個很好的解釋,我全神貫注。 無論如何,我現在解脫了!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM