首页 > 解决方案 > 错误:渲染的钩子比预期的少。这可能是由于意外提前退货声明造成的

问题描述

我总是收到错误

“错误:渲染的钩子比预期的少。这可能是由意外的提前返回语句引起的。”

这是错误

当我使用上下文和使用状态时,我的应用程序会做出本机反应。我想要的是连接应用程序周围的所有使用状态,但我总是收到此错误,但是当我在代码中保存时,应用程序会刷新(而不是重新启动)它工作正常。

这是 app .js 的代码

export default function App() {
  const [cart, setCart] = useState(null);
  const cartoo = useMemo(() => ({ cart, setCart }), [cart, setCart]);
  const Stack = createStackNavigator();

  return (
    <Context.Provider value={cartoo}>
      <NavigationContainer>
        <Stack.Navigator screenOptions={{ headerTintColor: '#8F5F43' }}>
          <Stack.Screen name="Home" component={Home} />
          <Stack.Screen name="Product" component={Product} />
        </Stack.Navigator>
      </NavigationContainer>
    </Context.Provider>
  );
}

产品.js

export const Product = ({ navigation, route }) => {
  const { cart, setCart } = useContext(Context);

  useEffect(() => {
    console.log('hello world');
  }, []);

  function momo() {
    setCart(route.params.studentData.id);
    console.log('item added');
  }
  return (
    <View>
      <TouchableOpacity
        style={{
          borderRadius: 10,
          marginTop: 10,
          width: '90%',
          height: 50,
          alignSelf: 'center',
          alignContent: 'center',
          justifyContent: 'center',
          backgroundColor: 'blue',
        }}
        onPress={() => momo()}
      >
        <Text style={{ alignSelf: 'center', color: 'white' }}>add to cart</Text>
      </TouchableOpacity>
    </View>
  );
};

标签: javascriptreactjsreact-nativereact-hooks

解决方案


推荐阅读