简体   繁体   中英

For i loop running infinitely React Native

I am currently writing an app in React Native and in it I have some save files stored in an array. In the code below, I loop through these saves and create a JSON version of the data ready to be transferred into XML using a separate function. The problem is that the code works, but runs infinitely and rather than creating a few buttons, creates a never ending amount (I have attached a screenshot). Any help would be greatly appreciated as I have been stuck on this for days and have tried everything!

export function sessionsViewer({ navigation, route }) {

  const [dataResults, setDatResults] = useState({ type: "View", children: [{}] })

  async function getDataResults() {
    var previousSaves = await getDataJSON('saves')
    for(let i = 0; i < previousSaves.length; i++){
      let prevSave = previousSaves[i]
      let json = {
        'type': 'View',
        'children': [
          {
            'type': 'Touchable',
            'styles': [styles.startButton, { width: widthPercentageToDP(90) }],
            'onpress': () => { alert('You pressed me!' + JSON.stringify(prevSave.scores)) },
            'children': [
              {
                'type': 'Text',
                'text': prevSave.technique + ': ' + prevSave.datetime,
                'styles': styles.buttonTXT
              }
            ]
          }
        ]
      }
      let prevDataResults = dataResults
      prevDataResults.children.push(json)
      setDatResults({ ...prevDataResults })
    }
  }

Image showing infinite list

You can add a global boolean variable like let control = false; . And set true before calling setDatResults.

control = true;
setDatResults({ ...prevDataResults })
control = false;

If we control this variable at the beginning of getDataResults function. This prevents the infinite loop.

async function getDataResults() {
    if (control) {
       return;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM