我正在使用 react native 来构建我的应用程序。 以下是我用来显示"标签"列表的代码。因此,该代码用于隐藏除前 2 个标签之外的所有标签,并且会出现一个"加载更多"链接。单击"加载更多"链接应该显示其余的标签。但是代码在我身上崩溃了。
this.state = {
visibleCount: 2,
};
<TextLink onPress={() => {
this.setState({visibleCount: mealTags.length});
}}
</TextLink>
我正在使用更改为状态来显示标签。谁能告诉我出了什么问题以及如何更新它?
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>
);
}
我得到的错误是这样的:由于未捕获的异常"RCTFatalException: Unhandle JS Exception: t.setState 不是函数"而终止应用。(在"t.setState({visibleCount:n.length}("中,"t.setState"未定义(",原因:"Unhandle JS Exception: t.setState 不是一个函数。(In 't.setState({visi..., stack: onPress@439:2034
您的MealTagsSection
是一个功能组件。React 功能组件不必包含本地状态。如果想要本地状态,那么您应该使其成为类组件。
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>
);
}
}