【发布时间】:2019-07-09 01:19:29
【问题描述】:
我正在构建一个从 API 检索博客文章数据的应用。该数据是一个对象数组。每个对象都有一个名为nid 的唯一键。当用户选择要阅读的博客文章时,我需要根据nid 获取正确的对象。尝试在我的 redux 存储中的数组上使用 Array.prototype.find() 方法在我的 BlogDetail.js 组件中使用时会引发错误。
我已经在componentDidMount() 以及render() 方法本身中使用此方法进行了测试。两者在某些情况下都可以工作,而在其他时候会因错误而失败,而两者之间没有任何更改。我还记录了Array.isArray(posts),以确保这确实是一个数组并且返回了true。我还能够使用 Redux DevTools 确认 state.content.blog.posts 条目在加载此组件时填充了数据。最后,我在 posts 数组上尝试了其他 Array 方法,它们产生了相同的结果。
我的组件 BlogDetail.js:
import React, { Component } from 'react';
import { Image, View } from 'react-native';
import { connect } from 'react-redux';
export class BlogDetail extends Component {
constructor(props) {
super(props)
}
render() {
const { navigation, posts } = this.props;
let post = posts.find(el => el.nid === navigation.getParam("nid"));
let BlogImage;
if (post.large_image && post.large_image !== '') {
BlogImage = <Image style={{ width: 500, height: 300, resizeMode: 'cover' }} source={{ uri: post.large_image }} />;
}
return (
<View>
{BlogImage}
<View style={{ margin: 20 }}>
<Text>{post.title}</Text>
// Some logic which needs the post ...
</View>
</View >
)
}
}
const mapStateToProps = state => {
return {
...state,
posts: state.content.blog.posts
}
}
export default connect(
mapStateToProps
)(BlogDetail);
state.content.blog.posts 数组示例:
[
{
nid: 123,
title: "A blog post",
body: "The quick brown fox jumped over the lazy dog",
large_image: "http://something.com/image",
},
{
nid: 234,
title: "Another Blog Post",
body: "Lorem ipsum something something",
large_image: "http://something.com/image2"
}
]
我希望这将过滤数组state.content.blog.posts 并显示我需要显示的特定帖子的信息。但是,当组件加载时,我会不一致地收到以下错误:
TypeError: posts.find() is not a function
【问题讨论】:
标签: reactjs react-native redux react-redux