gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:58:16 24 4
gpt4 key购买 nike

我有一个图像 url 数组,我正在尝试创建一个新对象,它应该如下所示:source: { uri: 'http://i.imgur.com/XP2BE7q.jpg' }

所以我使用 reduce() 来做到这一点。现在我想要修改后的 imageArray 并将其分配给名为 images 的状态变量(必须是数组),但我收到引用错误 imageArray not defined 为什么这样?

我想将新创建的 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 }} />;
}
}

最佳答案

试一试:

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

关于javascript - 从现有对象数组创建新对象数组时出现引用错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52668417/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com