【问题标题】:Invariant Violation: Text strings must be rendered within a <Text> component while using flatList不变违规:使用 flatList 时,文本字符串必须在 <Text> 组件中呈现
【发布时间】:2020-05-26 09:48:44
【问题描述】:

我正在使用平面列表来显示来自 unsplash api 的数据。但是在这里它一直在抱怨说这个

Invariant Violation:文本字符串必须在组件内呈现

我什至没有使用任何文本组件。我不知道这里出了什么问题。

App.js

export default function App() {
  const [loading, setLoading] = useState(true);
  const [image, setImage] = useState([]);
  const {height, width} = Dimensions.get('window');


  const URL = `https://api.unsplash.com/photos/random?count=30&client_id=${ACCESS_KEY}`;
  useEffect(() => {
    loadWallpapers();
  }, [])


  const loadWallpapers =() =>  {
    axios.get(URL)
    .then((res) => {

      setImage(res.data);
      setLoading(false);
    }).catch((err) => {
      console.log(err)
    }).finally(() => {
      console.log('request completed')
    })
  } 
  const renderItem = (image) => {
    console.log('renderItem', image);
    return (
      <View style={{height, width}}>
        <Image 
        style={{flex: 1, height: null, width: null}} 
        source={{uri : image.urls.regular}}/>

      </View>
    )
  }
  return loading ? (
    <View style={{flex: 1, backgroundColor: 'black', justifyContent: 'center',alignItems: 'center'}}>
      <ActivityIndicator size={'large'} color="grey"/>
    </View>
  ): (
    <SafeAreaView style={{flex: 1, backgroundColor: 'black'}}>
      <FlatList
        horizontal
        pagingEnabled
        data={image}
        renderItem={({ item }) => renderItem(item)} />}
      />
    </SafeAreaView>
  )
}

【问题讨论】:

  • 尝试使用 if else 代替三元运算符,这就是我所做的修复

标签: reactjs react-native react-native-android react-native-flatlist


【解决方案1】:

我的Flatlist的东西数据为空,试试

  <FlatList
    horizontal
    pagingEnabled
    data = {image ? image : []}
    renderItem={({ item }) => renderItem(item)} />}
  />

【讨论】:

    【解决方案2】:

    我需要做这样的事情才能让它发挥作用。

    const renderItem = ({ item }) => {   <---- I have destructured item here 
    console.log(item)
        return (
          <View style={{ flex: 1 }}>
    
          </View>
        );
      };
    
    <FlatList
              scrollEnabled={!focused}
              horizontal
              pagingEnabled
              data={image}
              renderItem={renderItem}
            />
    

    【讨论】:

      猜你喜欢
      • 2019-02-21
      • 2020-01-20
      • 2020-04-06
      • 2020-08-19
      • 1970-01-01
      • 2019-06-27
      • 2020-04-19
      • 1970-01-01
      相关资源
      最近更新 更多