功能组件中的钩子调用无效

时间:2021-06-26 08:44:39

标签: react-native react-hooks

我正在使用 React Native,但出现此错误: Render Error Invalid hook call. Hooks can only be called inside of the body of a function component...

问题是,我使用的钩子(useState)似乎没有问题,错误说我在这一行有问题:

const [isOpen, setIsOpen] = useState<boolean>(false);

我阅读了 Hooks 规则,但我认为这没有任何问题。

这是我的组件:

const GoalCard = (goal: IGoal) => { 
    const [isOpen, setIsOpen] = useState<boolean>(false);
    const btnsOpacity = useRef(new Animated.Value(0)).current;
    const initialeCardHeight = goal.deadline != undefined ? 150 : 80
    const cardHeight = useRef(new Animated.Value(initialeCardHeight)).current;
    
    
    const toggleCard = () => {
        setIsOpen(!isOpen);
        
        resizeCard();
        if(isOpen) {
            fadeOutBtns();
        } else {
            fadeInBtns();
        }
    }
}

这是我调用 toggleCard 的地方(在同一个文件中):

const renderDeadline = () => {
    return (
        <View style={styles.footer}>
            <View style={{display: 'flex', flexDirection: 'row', alignItems: 'center'}}>
                <Icon name="time-outline" size={28} color="#A0A4BA" style={{marginRight: 4}}/>
                <Text style={styles.deadlineText}>Deadline</Text>
                <Text style={styles.dateText}>test</Text>
            </View>
            <TouchableOpacity onPress={() => toggleCard()}>
                <Icon name={isOpen ? "chevron-up-outline" : "chevron-down-outline"} size={21} color="#A0A4BA"/>
            </TouchableOpacity>
        </View>
    )
}

renderDeadline 组件位于 GoalCard 内,我在 Hooks 规则中看到这可能是导致此错误的原因。 所以我尝试删除它,并直接在 renderDeadline 中使用 GoalCard 的 JSX,但我得到了同样的错误(尝试再次删除应用程序和 npm run iOS,而不仅仅是热重载)。

0 个答案:

没有答案