首页 > 解决方案 > 无法弄清楚为什么 React Hook 无效

问题描述

我正在尝试在我拥有的 React Native 页面中使用 useContext 钩子,我也在其他组件中使用这个钩子并且它们工作得很好,但是这个不会 - 无法弄清楚为什么。这是我的组件:

const GoalCard = (goal: IGoal) => {   
  const {theme} = useContext(ThemeContext); <-- error is here

  return (
    <Animated.View style={[styles.card, {height: cardHeight, backgroundColor: "#ff5e"}]}>
      <View>
         .....
      </View>
    </Animated.View>
  );

我在一个单独的文件中的 FlatList 中使用这个组件。

return (
    <SafeAreaView style={[styles.pageContainer, {backgroundColor: theme.background}]}>
      <FlatList
        showsVerticalScrollIndicator={false}
        style={{padding: 8}}
        data={goals}
        renderItem={({index}) => GoalCard(goals[index])}
        keyExtractor={item => item.id}
      />
    </SafeAreaView>
);

我收到错误:Invalid hook call,但这里似乎没有什么问题。看到一些关于此的问题,但没有一个有效,而且,根据Rules of Hooks页面似乎没有任何问题。为什么这里会发生这个错误?

编辑:这是我的 ThemeProvider:

function ThemeProvider({ children }) {
  const [dark, setDark] = React.useState(false);

  const toggle = () => {
    setDark(!dark); 
  }

  const theme = dark ? themes.dark : themes.light;

  return (
    <ThemeContext.Provider value={{theme, dark, toggle}}>
      {children}
    </ThemeContext.Provider>
  )
}

这是我的 App.tsx:

 <ThemeProvider>
      <Provider store={store}>
        <NavigationContainer>
             .....
        </NavigationContainer>
      </Provider>
    </ThemeProvider>

标签: react-nativereact-hooks

解决方案


推荐阅读