从现有的对象数组创建新的对象数组时出现引用错误?

3
我有一组图像URL的数组,我试图创建一个新对象,它应该如下所示:source:{ uri:'http://i.imgur.com/XP2BE7q.jpg' } 因此,我已经使用reduce()来完成这项工作。现在,我想要修改后的imageArray并将其分配给名为images的状态变量(必须是数组),但我却得到了"ReferenceError: 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 }} />;
  }
}

在构造函数中,您引用了尚未定义的imageArray。相反,使用空数组在状态中初始化图像,并在componentDitMount中创建imageArray并将其设置为状态。 - Tarek Essam
2个回答

1

Give this a try:

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 }} />;
  }
}

@Nguyen 如果我将代码移动到类组件之外,我会得到未定义的 images,而我正在对其进行映射,为什么会这样?请看这个 -> https://imgur.com/a/bSx0muV - fun joker
不行!“类组件外部”肯定行不通 :) - You Nguyen
@Nguyen 为什么?是什么原因? - fun joker
1
因为我们试图从props对象中获取images属性的值 :) ,所以props对象仅在类组件的实例内部可访问。 - You Nguyen
1
@Nguyen 抱歉,你的代码没问题,之前你使用了 componentDidMounted 而不是 componentDidMount :) - fun joker

1
您正在render方法中定义imageArray,这超出了constructor的范围。建议在定义图像数组后调用this.setState({images:imageArray});,而不是在render方法内部进行此操作。将state.images初始化为空数组。在componentDidMount中,缩小this.props.images,然后调用setState。

@Iarz 我应该将 reduce() 从类组件中移除吗?但是这样的话,this.props.images 还能正常工作吗? - fun joker
1
你可以随时访问你的props。我要修改我的初始回答并建议你在构造函数中将图像设置为空数组,然后在componentDidMount中进行this.props.images.reduce操作,并使用setState更新状态。 - larz
如果我将代码移动到类组件之外,我会得到未定义的 images,而我正在对其进行映射,为什么会这样?请看这个 -> https://imgur.com/a/bSx0muV - fun joker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接