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

问题描述 投票:1回答:1

当用户点击按钮时,我正试图在彼此之后运行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)

有谁知道如何解决这个问题?

reactjs asynchronous solidity ipfs
1个回答
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
    }
© www.soinside.com 2019 - 2024. All rights reserved.