javascript - React 不会访问嵌套状态

标签 javascript reactjs

我已将 React 状态设置为来自 API 的数据

this.setState({贷款:response.data})

response.data 是一个嵌套对象

{
  application: {
    amount: 20,
    interest: 10,
    guarantor: {
      firstName: "John",
      lastName: "Doe"
    }
  },
  userId: "123"
}

通常在渲染函数内我可以访问

<p>{this.state.loan.userId}</p>
<p>{this.state.loan.application.amount}</p>
<p>{this.state.loan.application.guarantor.firstName}</p>

现在我只能访问贷款的第一个 child 。除了我实际上设置了对象中每个单独项目的状态。注意 console.log(this.state.loan.application.guarantor) 工作正常。

这是 API 调用

fetch(`http://localhost:8000/api/v1/loans/${this.state.id}`)
    .then(res => {
      return res.json();
    }).then(response => {
      this.setState({loan: response.data});
    })
    .catch(err => console.log(err));
const {loan} = this.state;
<div className="col-md-4">
    <h5 className="title">Full Name</h5>
    <p>{loan.fullName}</p>
    <h5 className="title mt-3">Account Number</h5>
    <p>{loan.accountNumber}</p>
    <h5 className="title mt-3">Phone Number</h5>
    <p>Phone Number</p>
</div>
<div className="col-md-4">
    <h5 className="title">Loan Amount</h5>
    <p>
        {(loan.application.amount).toLocaleString("en-NG", {
        style: "currency",
        currency: "NGN"
        })}
    </p>
    <h5 className="title mt-3">Interest Rate</h5>
    <p>{loan.interestRate}%</p>
    <h5 className="title mt-3">Duration</h5>
    <p>{loan.duration} Months</p>
</div>

API调用的响应

{
            "application": {
                "guarantor1": {
                    "fullName": "Ayebakuro Ombu",
                    "residentialAddress": "30 Udengs Eradiri Avenue Off Azikoro Village Road",
                    "occupation": "Accountant",
                    "netIncome": "50000",
                    "placeOfWork": "Dreamworld",
                    "employer": "Ayebakuro Ombu",
                    "relationship": "Employer",
                    "bvn": "0101010101",
                    "bank": "GTBank",
                    "accountNumber": "10101010101",
                    "phoneNumber": "010101010101"
                },
                "guarantor2": {
                    "fullName": "Ayebakuro Ombu",
                    "residentialAddress": "B48 Copa Cobana Estate, Wumba, Lokogoma",
                    "occupation": "business man",
                    "netIncome": "500000",
                    "placeOfWork": "Dreamworld",
                    "employer": "SafeScrow Tech",
                    "relationship": "Employer",
                    "bvn": "0101010101",
                    "bank": "GTBank",
                    "accountNumber": "0101010101",
                    "phoneNumber": "0101010101"
                },
                "mode": {
                    "name": "DreamWorld Savings And Loans Ltd",
                    "address": "30 Udengs Eradiri Avenue Off Azikoro Village Road",
                    "netIncome": "50000"
                },
                "bankDetails": {
                    "bank": "Parallex Bank",
                    "accountNumber": "0101010101",
                    "bvn": "0101010101"
                },
                "amount": 200000,
                "number": "25642",
                "date": "2019-03-22T02:37:58.069Z",
                "purpose": "For debt payment"
            },
            "approval": {
                "amount": 0,
                "status": "Pending"
            },
            "issue": {
                "status": false
            },
            "payment": {
                "schedule": [],
                "completed": false
            },
            "_id": "5c944a86abf7ea09c40301e5",
            "accountNumber": "1000000002",
            "fullName": "Ayebakuro Ombu",
            "type": "Business",
            "duration": 5,
            "interestRate": 10,
            "__v": 0
        }

错误:LoanPage.js:61 Uncaught TypeError: 无法读取未定义的属性“amount” 在 LoanPage.render (LoanPage.js:61)

正确记录 this.state.loan.application.amount 日志

最佳答案

当组件被渲染时(如下面的代码),React 立即调用相应组件的 render 方法。

ReactDom.render(<LoanPage />, element);

如果您要在构造函数或 componentWillMount 方法中执行异步 fetch 事件,这不会阻止 React 系统执行渲染。

这就是解决这个问题的方法。在构造函数/componentWillMount 中,您应该设置 this.state.loading = true ,然后触发 fetch 调用。在 fetch 调用的 .then 部分,setState 清除加载标志,如下所示:

this.setState({
    loading: false,
    loan: response.data
});

LoanPage 的 render 方法现在可以从“正在进行的获取调用”的知识中受益,如下所示:

render() {
    if(this.state.loading) {
        return (<h3>Loading...</h3>);
    }

    return (
        <div> Loan amount is {this.state.loan.application.amount} </div>
    );
}

您可以更改渲染的第一部分(在 if 条件下)以显示微调器或类似的东西。您应该更改第二部分以渲染您现在正在渲染的所有内容。

关于javascript - React 不会访问嵌套状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55292631/

相关文章:

javascript - 是否可以使用 React Navigation 在 React Native 中的自定义和默认转换之间切换?

javascript - 将 props 传递给组件的首选样式

javascript - 如果我需要更新 2 个依赖变量,React hooks 如何只执行一次副作用函数

javascript - 如何在 Javascript 中使用异步等待函数对象?

javascript - 在 ng-class 中删除和添加类

javascript - EXT JS 64 位 Internet Explorer 渲染问题?

javascript - Next.js 错误 : Hydration failed because the initial UI does not match what was rendered on the server

javascript - 评估 JSON 字符串 - eval() 与 new Function()

javascript - 如何构建不改变的DOM的缓存

css - React - 组件全屏(高度 100%)