【问题标题】:react-native | Loop on rendering Items of FlatList反应原生 |循环渲染 FlatList 的项目
【发布时间】:2020-05-05 05:24:25
【问题描述】:

我会为这个Item 创建一个FlatList

function Item({ marca, targa, index, allData, jwt }) {

  const [modalVisible, setModalVisible] = useState(false);
  const [encData, setEncData] = useState('');

  console.log(jwt);
  console.log(allData);

  const content = {
    data: allData
  }

  fetch('https://example.com/api/encrypt', {
    method: 'POST',
    body: JSON.stringify(content),
    headers: {
      'Content-Type': 'application/json; charset=utf-8',
      'authorization': jwt
    }
  })
  .then(response => response.json())
  .then(res => setEncData(res.message))
  .catch(err => console.log(err));

  return (
    <React.Fragment>
      <Modal
        animationType='fade'
        transparent={false}
        visible={modalVisible}
        onRequestClose={() => {
          Alert.alert('Modal has been closed.');
        }}
      >
        <View style={{flex:1, justifyContent: 'center', alignItems: 'center' }}>
          <View style={styles.modalInsideView}>                  
            <View style={{bottom: 50}}>
              <Text style={[styles.buttonText, styles.medium]}>{marca}   <Text style={styles.buttonText}>-   {targa}</Text></Text>
            </View>

            <Text>{JSON.stringify(encData)}</Text>

            <View style={{alignItems: 'center', justifyContent: 'center'}}>
              <TouchableOpacity style={[styles.button, {backgroundColor: '#00b0ff'}]} onPress={ () => setModalVisible(!modalVisible) }>
                <Ionicons
                  name={'ios-close'}
                  size={40}
                  style={{ color: 'white' }}
                />
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Modal>
      <TouchableOpacity 
        style={[styles.infoVehicle, {marginTop: index === 1 ? 10 : 18}]}
        onPress={ () => setModalVisible(true) }>
        <View style={{flexDirection:'row', alignItems: 'stretch', alignItems: 'center', justifyContent: 'space-between'}}>
          <View style={{}}>
            <Text style={[styles.buttonText, styles.medium]}>{marca}   <Text style={styles.buttonText}>-   {targa}</Text></Text>
          </View>
          <View style={{}}>
            <Image
              style={{width: 40, height: 40, opacity: 0.5}}
              source={require('../../images/qr-example.png')}
            />
          </View>
        </View>
      </TouchableOpacity>
    </React.Fragment>
  );
}

但是,我意识到&lt;Text&gt;{JSON.stringify(encData)}&lt;/Text&gt;元素的内容不断变化,好像Item函数正在循环。为什么?

link,您可以找到我为该页面编写的所有代码。

【问题讨论】:

    标签: react-native expo react-native-flatlist


    【解决方案1】:

    我可以看到你正在把这部分放在渲染函数中:

    fetch('https://example.com/api/encrypt', {
        method: 'POST',
        body: JSON.stringify(content),
        headers: {
          'Content-Type': 'application/json; charset=utf-8',
          'authorization': jwt
        }
      })
      .then(response => response.json())
      .then(res => setEncData(res.message))
      .catch(err => console.log(err));
    

    React 可能会多次调用函数 Item() 进行渲染,每次都会引入一个新的 API 调用,当 api 调用成功时依次调用setEncData。这引入了状态更改,React 将再次调用 Item() 重新渲染,然后引入循环。要解决此问题,您可以将 fetch() 放入 useEffect 中,如下所示:

    useEffect(() => {
    const content = {
        data: allData
      }
    fetch('https://example.com/api/encrypt', {
        method: 'POST',
        body: JSON.stringify(content),
        headers: {
          'Content-Type': 'application/json; charset=utf-8',
          'authorization': jwt
        }
      })
      .then(response => response.json())
      .then(res => setEncData(res.message))
      .catch(err => console.log(err));
    }, []) // make this an empty array
    
    

    更新:allData 可能是一个对象,不会通过浅层相等检查

    【讨论】:

    • 感谢您的建议,但问题依然存在
    • @th3g3ntl3man 我刚刚更新了我的答案,让我们试试那个版本
    猜你喜欢
    • 2020-06-29
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    相关资源
    最近更新 更多