Reputation: 12431
I am using react native to build my app. Below is the code I am using to display a list of 'tags'. So the code is used to hide all the tags except for the first 2, and a 'load more' link will appear. Clicking on the load more link is supposed to show the rest of the tags. However the code crashes on me.
this.state = {
visibleCount: 2,
};
<TextLink onPress={() => {
this.setState({visibleCount: mealTags.length});
}}
</TextLink>
I am using changing to state to show the tags. Can anyone advise me on what went wrong and how I can update it?
export function MealTagsSection(props: MealTagsProps) {
let {mealTags} = props;
let loadMoreLink;
if (mealTags.length > 2) {
loadMoreLink = (
//THIS CAUSES THE APP TO CRASH
<TextLink onPress={() => {
this.setState({visibleCount: mealTags.length});
}}
>
load more...
</TextLink>
);
} else {
loadMoreLink = null;
}
this.state = {
visibleCount: 2,
};
return (
<View style={styles.mealTagsContainer}>
{
mealTags.slice(0, this.state.visibleCount).map((mealTag) => {
let tagStyle = '';
if (mealTag.category === 1) {
tagStyle = styles.tag_healthy;
} else {
tagStyle = styles.tag_improve;
}
return (
<View style={tagStyle}>
<Text style={styles.tagText}>{mealTag.description}</Text>
</View>
);
})
}
{loadMoreLink}
</View>
);
}
The error I am getting is this: *** Terminating app due to uncaught exception 'RCTFatalException: Unhandled JS Exception: t.setState is not a function. (In 't.setState({visibleCount:n.length})', 't.setState' is undefined)', reason: 'Unhandled JS Exception: t.setState is not a function. (In 't.setState({visi..., stack: onPress@439:2034
Upvotes: 1
Views: 1236
Reputation: 8065
Your MealTagsSection
is a functional component. React functional component doesn't have to way to include a local state. If want to have local a state then you should make it a class component.
export class MealTagsSection extends Component {
constructor() {
super();
this.state = { visibleCount: 2 };
}
render() {
let { mealTags } = this.props;
let loadMoreLink;
if (mealTags.length > 2) {
loadMoreLink =
(
<TextLink
onPress={() => {
this.setState({ visibleCount: mealTags.length });
}}
>
load more...
</TextLink>
);
} else {
loadMoreLink = null;
}
return (
<View style={styles.mealTagsContainer}>
{mealTags.slice(0, this.state.visibleCount).map(mealTag => {
let tagStyle = "";
if (mealTag.category === 1) {
tagStyle = styles.tag_healthy;
} else {
tagStyle = styles.tag_improve;
}
return (
<View style={tagStyle}>
<Text style={styles.tagText}>{mealTag.description}</Text>
</View>
);
})}
{loadMoreLink}
</View>
);
}
}
Upvotes: 2