反应异步方法setState变量未及时设置

时间:2019-03-28 22:42:36

标签: reactjs asynchronous solidity ipfs

当用户单击按钮时,我试图依次运行3种方法

步骤:

1:将文件推送到IPFS,重新获得链接并将其分配给状态变量

2:将该链接(来自该var)添加到区块链智能合约

3:向Firebase数据库添加一个条目

问题是,当我尝试将IPFS链接传递到智能合约时,该IPFS链接为空,但是在该方法运行后,我可以看到链接打印到控制台。 因此,我猜测下一个方法没有及时设置该变量。

IPFS方法:

pushToIPFS = async(e) => {
      //  e.preventDefault()
        await ipfs.add(this.state.buffer, (err, ipfsHash) => {
            console.log(err, ipfsHash)
            //this.setState({IPFSlink : ipfsHash[0].hash})
            console.log(ipfsHash[0].hash)
            return ipfsHash[0].hash
        })
    }

区块链方法:

addToBlockchain = async(e) => {
        //create a new key for our student
        var key = this.state.StudentNumber + this.state.account[0]
        key = parseInt(hash(key), 10)
        this.setState({idForBlockchain: key})
        console.log(key)

        //get todays date
        let newDate = new Date()
        newDate = newDate.getTime()
        var _ipfsLink = this.state.IPFSlink
        var _account = this.state.account[0]
        console.log(_ipfsLink)
        console.log(this.state.IPFSlink)
        await storehash.methods.sendDocument(_ipfsLink, newDate, 


    }

Firebase方法:

createStudent = async(e) => {
        //get student details from state variables & current user uid
        var _uid = this.state.uid
        var _studentName = this.state.StudentName
        var _studentNumber = this.state.StudentNumber
        var _courseCode = this.state.CourseCode
        var _courseName = this.state.CourseName
        var _idForBlockchain = this.state.idForBlockchain

        // database.ref.students.uid.studentNumber 
        const db = firebase.database()
        db.ref().child("students").child(_uid).child(_studentNumber).set(
            {   studentName: _studentName,
                courseCode: _courseCode,
                courseName: _courseName,
                blockchainKey: _idForBlockchain 
            }
        );

        alert("Student added")

    }

单击按钮时触发的方法:

AddMyStuff = async (e) => {
        e.preventDefault()
        await this.pushToIPFS()
        await this.addToBlockchain()
        await this.createStudent()
    }

这是返回的错误,所以我认为是await和setState引起了问题,并且没有设置我需要的变量。

  

未处理的拒绝(错误):无效的字符串值(arg =“ _ ipfsLocation”,coderType =“ string”,value = null,version = 4.0.27)

有人知道如何解决吗?

1 个答案:

答案 0 :(得分:0)

您可以将pushToIPFS转换为Promise而不是回调,并在触发回调后解决它。

pushToIPFS = (e) => {
    return new Promise((resolve, reject) => {
          ipfs.add(this.state.buffer, (err, ipfsHash) => {
            resolve(ipfsHash[0].hash);
        })
    });
}

由于它是一个承诺,因此您可以使用async/await

AddMyStuff = async (e) => {
        e.preventDefault()
        const ipfsHash = await this.pushToIPFS();
        //you have your ipfsHash defined, you can pass it to your other methods
    }