【发布时间】:2022-02-07 18:02:15
【问题描述】:
我是新来的反应原生和实现一个平面列表。在平面列表的渲染项中,我正在渲染一个功能组件,如果用户选择或取消选择它,我想使用状态来更改图像。
我面临的问题是抛出无效的钩子调用。我尝试了所有教程,但它显示的描述状态的方式完全相同。
const NewsItem = (props, item, onFavouriteSelect, index) => {
const[isFavourite,setFavourite] = useState(false);
return<Text>Random text for stackoverflow</Text>
}
平面列表代码:
render() {
return (
<View style={styles.container}>
{this.state.newsList.length > 0 ? (
<FlatList
showsVerticalScrollIndicator={false}
data={this.state.newsList}
renderItem={({item, index}) =>
NewsItem(
this.props,
item,
this.onFavouriteSelect.bind(this),
index,
this.state.isFavourite,
)
}
/>
) : (
<LoadingScreen />
)}
</View>
);
}
react、react dom 和 react native 的版本如下:
"react": "17.0.2",
"react-dom": "17.0.2",
"react-native": "0.67.2",
它抛出的错误是:
Invalid hook call. Hooks can only be called inside of the body of a function component.
This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
谢谢。
更新代码:
class HomeScreen extends Component {
state = {
newsList: [],
IdsList: [],
isFavourite: false,
};
isFavouriteItem(index) {
if (this.state.IdsList.indexOf(index) === -1) {
return false;
} else {
return true;
}
}
render(){
return(){
<FlatList
showsVerticalScrollIndicator={false}
data={this.state.newsList}
renderItem={({item, index}) =>
NewsCell(
this.props,
item,
this.onFavouriteSelect.bind(this),
index,
this.isFavouriteItem(index),
this.state.isFavourite,
)
}
/>
}}
我添加的更新代码现在可以工作了。但这是一个好方法吗?
【问题讨论】:
-
请与 flatlist 分享您的完整代码
-
我已经添加了平面列表代码。请看看@NooruddinLakhani
标签: react-native