簡體   English   中英

從現有對象數組創建新的對象數組時出現引用錯誤?

[英]Getting referrence error while creating new array of object from existing array of objects?

我有一個圖像網址數組,我正在嘗試創建一個新的對象,它應該是這樣的: source: { uri: 'http://i.imgur.com/XP2BE7q.jpg' }

所以我用reduce()來做到這一點。 現在我想要修改的imageArray並為其分配狀態變量,稱為images(必須是一個數組)但是我得到引用錯誤imageArray沒有定義為什么會這樣?

我想將新創建的imageArray分配給狀態變量,我該怎么做? 目前,我得到引用錯誤我應該在類組件外移動reduce()操作。

碼:

export default class ImageView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      index: 0,
      images: imageArray
    };
  }
  render() {
    const imageArray = this.props.images.reduce((acc, images) => {
      let temp = {
        source: {
          uri: images
        }
      };

      acc.push(temp);
      return acc;
    }, []);
    console.log(imageArray);
    return <View style={{ flex: 1 }} />;
  }
}

您在render方法中定義了imageArray ,這超出了constructor的范圍。 我建議調用this.setState({ images: imageArray }); 定義圖像數組后,不應該在render方法中進行。 將state.images初始化為空數組。 componentDidMount ,減少this.props.images ,然后調用setState

嘗試一下:

export default class ImageView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      index: 0,
      images: []
    };
  }
  componentDidMount() {
    const imageArray = this.props.images.reduce((acc, images) => {
      let temp = {
        source: {
          uri: images
        }
      };

      acc.push(temp);
      return acc;
    }, []);

    this.setState({ images: imageArray });
  }
  render() {
    return <View style={{ flex: 1 }} />;
  }
}

暫無
暫無

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

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