发布内容时出错:-散布不可分割实例的无效尝试。 为了不出错,非数组对象必须具有一个Symbol。迭代器方法。
我认为它发生在添加帖子中,但不解释为什么它发生。有人可以告诉我为什么吗? 我不知道是什么原因导致错误或原因
这是我的代码
class Home extends Component {
state = {
modal: false,
post: [
{
key: "1",
title: "A Good Boi",
des: "He's a good boi and every one know it.",
image: require("../assets/dog.jpg"),
},
{
key: "2",
title: "John Cena",
des: "As you can see, You can't see me!",
image: require("../assets/cena.jpg"),
},
],
};
addPost = (posts) => {
posts.key = Math.random().toString();
this.setState((prevState) => {
return {
post: [...prevState.posts, posts],
modal: false,
};
});
};
closeModal = () => {
this.setState({ modal: false });
};
deleteItem = (item) => {
Alert.alert("Delete", "Are You Sure?", [
{
text: "Yes",
onPress: () =>
this.setState({
post: this.state.post.filter((p) => p.key !== item.key),
}),
},
{ text: "no" },
]);
};
render() {
return (
<Screen style={styles.screen}>
<Modal visible={this.state.modal} animationType="slide">
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<View style={styles.modalContainer}>
<AddPost addPost={this.addPost} />
</View>
</TouchableWithoutFeedback>
</Modal>
<FlatList
data={this.state.post}
renderItem={({ item }) => (
<>
<Card
title={item.title}
subTitle={item.des}
image={item.image}
onPress={() => this.props.navigation.navigate("Details", item)}
/>
</>
)}
/>
<FloatButton
name="plus"
onPress={() => this.setState({ modal: true })}
/>
答案 0 :(得分:0)
您在addPost
中拥有
// the previousState is initialized with post, not posts
post: [...prevState.posts, posts]
但是您可能的意思是
post: [...prevState.post, posts]
总体而言,您的命名似乎令人困惑。如果该州明确拥有职位列表,则该属性应命名为posts
,而不仅仅是post
。
您的addPost
函数建议它以单个帖子作为参数,但是您将参数命名为posts
而不是post
。您应该将其更改为如下所示:
state = {
modal: false,
posts: [ /* ... */ ],
};
addPost = post => {
post.key = Math.random().toString();
this.setState((prevState) => {
return {
posts: [...prevState.posts, post],
modal: false,
};
});
};