reactjs 无法读取null的属性(阅读“useState”)TypeError:无法读取null的属性(阅读“useState”)

vngu2lb8  于 2023-04-11  发布在  React
关注(0)|答案(1)|浏览(294)

我正在构建一个react-native应用程序。一旦我初始化状态,我就会得到这个错误反馈:
无法读取null的属性(阅读“useState”)TypeError:无法读取null的属性(阅读“useState”)
我在以下规范上运行react-native:

"native-base": "^2.8.2",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-native": "0.71.6",
    "react-native-swiper": "^1.6.0",
    "react-native-web": "~0.18.10"

我试过重新安装react,都降级了,还是不行。这是我的代码示例。一旦你注解了useState和useEffect,应用程序就可以正常工作了。

import { StyleSheet, Text, View } from 'react-native';
import React,{ useState, useEffect } from 'react';

const data = require('../../assets/data/products.json');

const [products, setProducts] = useState([]);

useEffect(() => {
            setProducts(data);
    
            return () => {
                setProducts([])
            }
        }, [])

const productContainer = () => {
  return (
    <View>
      <Text>products </Text>
    </View>
  )
}

export default productContainer;

const styles = StyleSheet.create({})
3ks5zfa0

3ks5zfa01#

useStateuseEffect需要在productContainer内部,而不是外部。

import { StyleSheet, Text, View } from 'react-native';
import React,{ useState, useEffect } from 'react';

const data = require('../../assets/data/products.json');

const productContainer = () => {
    const [products, setProducts] = useState([]);

    useEffect(() => {
        setProducts(data);
    
        return () => {
            setProducts([])
        }
    }, [])

  return (
    <View>
      <Text>products </Text>
    </View>
  )
}

export default productContainer;

const styles = StyleSheet.create({})

相关问题