【问题标题】:ReactJS: Unable to parse through a 2d array outside async functionReactJS:无法解析异步函数之外的二维数组
【发布时间】:2019-06-27 07:45:59
【问题描述】:

尝试在异步函数中设置数组的状态,并在异步函数中访问它可以正常工作。但是当我尝试在异步函数之外访问它时,它只解析第一层,意思是 bookDetails[0],而解析 bookDetails[0][0] 时会给出错误“cannot-read-property-0-of-undefined "

getAll = async () => {
    const { contract } = this.state;
    const response = await contract.methods.getBooks().call();
    this.setState({ bookDetails: response});
    console.log("books: ",this.state.bookDetails[0][0]);

  };


//OUTPUT=> books:  nanme

//console.log outside the async function gives error

【问题讨论】:

    标签: arrays reactjs mapping solidity


    【解决方案1】:

    注意 setState 本身并不同步,您必须在其回调中检查更新状态:

    getAll = async () => {
        const { contract } = this.state;
        const response = await contract.methods.getBooks().call();
        this.setState({ bookDetails: response}, () => console.log("books: ",this.state.bookDetails[0][0]);
    );};
    

    除此之外,sn-p 不足以验证为什么无法正确登录的外部异步功能。请提供更完整的sn-p。

    【讨论】:

      猜你喜欢
      • 2018-02-17
      • 2022-01-03
      • 2016-03-30
      • 1970-01-01
      • 1970-01-01
      • 2021-12-22
      • 1970-01-01
      • 2020-01-14
      • 1970-01-01
      相关资源
      最近更新 更多