在React Native中设置功能顺序

时间:2018-07-31 20:37:41

标签: javascript react-native

我在componentDidMount内部有2个函数

componentDidMount() {
    this.m1();
    this.m2();
}

m1下载了我在m2中使用的文件,但是当我运行该应用程序时出现错误,因为m2在m1之前运行。

是否可以设置我想要的顺序,以便m1首先下载文件然后运行m2?

2 个答案:

答案 0 :(得分:0)

您始终可以使用类似的回调

     updateState = (index,isSelected) => {
        this.setState((prevState) => {
            return update(prevState.options,{
                [index]: {
                    isSelected:{$set: isSelected}
                }
            })
        })
    }

    handleClick(e) {
        this.state.options.map((option, i) => {

            const isSelected = option.optionName == e.target.id;

            this.updateState(i, isSelected);
        })     
      }


    componentDidUpdate(){
        console.log(this.state.options)
    }

答案 1 :(得分:0)

在某些情况下,如果使用诺言,这些功能可能会更高效,更易读。承诺可以帮助您避免所有“回调地狱”,并且将来您将能够以最简单的方式理解任何异步和嵌套函数的所有功能。

例如(您应该将代码多次调用才能看到错误或成功)

const myAsyncFuntion = () => {
  return new Promise ((resolve, reject) => {
    //Some Logic for example a random number betweeen 1 and 10.
    //randomNumber should be smaller than 5. if not, the mySyncFuntion wont be called
    var myRandomNumber = Math.floor((Math.random() * 10) + 1);
    setTimeout(() =>{      
      if(myRandomNumber <= 5){
        console.log('AsyncFunction with randomNumber = ' + myRandomNumber)
        resolve(myRandomNumber);
      }else{
        console.log('AsyncFunction, with randomNumber = ' + myRandomNumber)
        reject(new Error('randomNumber ' + myRandomNumber + ' is bigger than 5'))
      }
    }, 1000)
  })
};

const mySyncFunction = (number) => {
  //Some Logic
    console.log('SyncFunction, randomNumber as param =>' + number)
};


//MAIN SYNCHRONOUS FUNCTION 
 var consoleLOGS = myAsyncFuntion()
  .then((response) => { //first response from the resolve() method
    mySyncFunction(response)
    return  (response) // you can pass the response to second then() method
  })
  .then((newResponse) => console.log('success, mySyncFunction executed, param recived in 2nd then = ' + newResponse))
  .catch((error) => console.log('error, mySyncFunction wasnt executed, ' + error.message))

请注意,尽管异步功能需要1000毫秒才能执行,但它比同步功能console.log()的主要功能要先运行,这需要更少的时间。不要忘记在componentDidMount()方法中应该调用...

myAsyncFuntion()
 .then((response) => { 
     mySyncFunction(response)
     return  (response) // you can pass the response to second then() method
   })
 .then((newResponse) => console.log('success... second then = ' + newResponse))
 .catch((error) => console.log('error catched, ...' + error.message))

最后,如果在主组件上定义了函数的定义,则它们的类型应为const。回调相当不错,但Promises更好,可读性更好。我确信您可以使用Promises做更多的逻辑和实现。

如果要处理API请求,则可以使用axios或fetch。也许您将Firebase用作数据库,并且THENABLE是许多功能,这意味着您可以访问then和catch方法,因为服务器返回了Promises。

在这里https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise