【问题标题】:TypeError: Undefined is not an object - React NativeTypeError: Undefined is not an object - React Native
【发布时间】:2020-03-05 11:19:49
【问题描述】:

我是开发的初学者,我得到 Undefined is not an object 错误。我在这里做错了什么?当我控制台记录 placeID 时,它返回值,但 selectedPlace 返回未定义。谢谢。

const PlaceDetailScreen = props => {
  const [places, setPlaces] = useState([])

  useEffect(() => {
    const getPlaces = async () => {
      const result = await axios.get('https://tgr-admin.appspot.com/api/places')

      setPlaces(result.data)
    }

    getPlaces()
  }, [])

  const placeID = props.navigation.getParam('placeId')

  const selectedPlace = places.find(place => place._id === placeID)

  return (
    <ScrollView>
      <Image source={{ uri: selectedPlace.image }} style={styles.image} />
    </ScrollView>
  )
}

【问题讨论】:

    标签: react-native


    【解决方案1】:

    问题在于 selectedPlace,在 getPlaces 完成之前,places 是一个空数组并且 .find > 方法返回未定义。访问 selectedPlace undefined 上的图像道具会引发错误。在访问 selectedPlace 上的图像道具之前执行 null 检查。

    const PlaceDetailScreen = props => {
      const [places, setPlaces] = useState([])
    
      useEffect(() => {
        const getPlaces = async () => {
          const result = await axios.get('https://#')
    
          setPlaces(result.data)
        }
    
        getPlaces()
      }, [])
    
      const placeID = props.navigation.getParam('placeId')
    
      const selectedPlace = places.find(place => place._id === placeID)
      // selectedPlace is undefined and places equals []
      // perform null check before accessing image prop
      return (
        <ScrollView>
          <Image source={{ uri: selectedPlace && selectedPlace.image }} style={styles.image} />
        </ScrollView>
      )
    }
    
    

    【讨论】:

    • 成功了,非常感谢,你很棒。 :) 如果您有时间,我还想再问 1 个问题。当我使用过滤器方法而不是查找时,它返回一个数组。但是当我控制台记录 selectedPlace.image 时,它​​是未定义的。这是什么原因?再次非常感谢您。
    • filter 方法返回过滤对象的数组,所以访问第一个数组元素然后访问 image prop,就像这样selectedPlace[0] &amp;&amp; selectedPlace[0].image
    【解决方案2】:

    根据 Aadil Mehraj 的回答,使用 null 检查包装内容也可以。所以我可以在里面添加更多的东西。

      return (
        <ScrollView>
          {selectedPlace && (
            <>
              <Image source={{ uri: selectedPlace.image }} style={styles.image} />
    
              <View style={styles.container}>
                <MarkdownView styles={markdownStyles}>
                  {selectedPlace.content}
                </MarkdownView>
              </View>
    
            </>
          )}
        </ScrollView>
      )
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-30
      • 2020-08-31
      • 2020-04-02
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多