简体   繁体   English

反应本机中的无效挂钩调用问题

[英]Invalid hook call problem in react native

I have problem with hook call in react native.我对本机反应中的钩子调用有问题。 I checked version of dom and react native and it looks right.我检查了 dom 的版本并做出了本机反应,它看起来不错。 I think the problem is function in my code, but I dont have any errors.我认为问题是我的代码中的 function ,但我没有任何错误。

Here is my function:这是我的 function:

function ReadingComponent () {

    
    const redirectTo = (screenName: any) => {
        useNavigation().navigate(`${screenName}`);
    }

Here is flatlist:这是平面列表:

       const categories = [ 
        {
            name : "Category 1",
            img : require("../Assets/Slika.jpg"),
            screenName : "Player",
        },
        {
            name : "Category 2",
            img : require("../Assets/Slika.jpg"),
            screenName : "Player1",
        },

And here are flatlist details with onPress:以下是 onPress 的平面列表详细信息:

return (
            <View style={styles.container}>
                <FlatList
                    data={categories}
                    showsHorizontalScrollIndicator={false}
                    numColumns={categories.length / 5}
                    showsVerticalScrollIndicator={false}
                    renderItem = {({item, index}) => {
                        return (
                        <TouchableOpacity 
                            onPress={() => redirectTo(item.screenName)}>
                        <Surface style={styles.surface}>
                            <ImageBackground
                            source={item.img} 
                            style={styles.img}
                            blurRadius={0.5}>
                        <Icon name="music" color="#fff" size={22}/>
                        <Text style={styles.name}>{item.name}</Text>
                            </ImageBackground>
                        </Surface>
                        </TouchableOpacity>
                        );
                    }}
                />
            </View>
            
        );    
    }
export default ReadingComponent;

You are denying React's Rules of Hooks : https://reactjs.org/docs/hooks-rules.html你否认 React 的Hooks 规则https://reactjs.org/docs/hooks-rules.html

useNavigation() is a hook and it cannot be called conditionally (eg in a function) useNavigation()是一个钩子,不能有条件地调用它(例如在函数中)

instead, you can write your code as follows:相反,您可以按如下方式编写代码:

 const navigation = useNavigation();
 const redirectTo = (screenName: any) => {
     navigation.navigate(`${screenName}`);
 }

I suggest reading the Rules of Hooks link carefully, and even for more deeper understanding you can search for how react hooks are implemented.我建议仔细阅读Rules of Hooks 链接,甚至为了更深入地了解,您可以搜索react hooks 是如何实现的。 Then you will truly know why order matters in React hooks.然后你就会真正知道为什么顺序在 React 钩子中很重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM