【问题标题】:Accses json data from API to frontend Reactjs将 json 数据从 API 访问到前端 Reactjs
【发布时间】:2019-08-03 22:51:46
【问题描述】:

我想制作一个应用程序,在您的保险到期时提醒您,并且我想访问我的数据库中的数据以制作一个编辑表单并用这些数据填充字段。我在 InsurancesController 中有这个功能:

public function edit($insurance)
{
    $insurance = Insurance::whereId($insurance)->first();

    return response() -> json([
        'insurance' => $insurance
    ]); 
}

我有这条路线:

<Route path="/:id/edit" exact render={props => (
     <EditInsurance {...props} insurances={this.state.insurances} />)}
 />

我有这个组件,只是为了测试:

import React, { Component } from "react";

class EditInsurances extends Component {
  render() {
    const { insurances } = this.props;
    return (
      <div>
        <p>Hello</p>
        {insurances.map(insurance => (
          <p>{insurance.id}</p>
        ))}
      </div>
    );
  }
}

export default EditInsurances;

如何仅访问我要编辑的保险?

编辑

这是我使用邮递员时得到的结果:reminderapi.test/api/insurances/5/edit :

{
    "insurance": {
        "id": 5,
        "user_id": 1,
        "tip": "Asigurare",
        "date_exp": "1975-12-28",
        "date_notif": "2006-06-19",
        "note": "Vitae dolorem corporis impedit eligendi laborum quidem.",
        "created_at": "2019-03-11 09:49:23",
        "updated_at": "2019-03-11 09:49:23"
    }
}

【问题讨论】:

  • 你需要更清楚你的疑问。发布更多详细信息。
  • 我想访问我在控制器 (json) 中发送到我的编辑路线的数据
  • 你能发布你在请求中发送的数据吗?
  • 这是我使用邮递员时得到的结果:reminderapi.test/api/insurances/5/edit :{ "insurance": { "id": 5, "user_id": 1, "tip": "Asigurare", "date_exp": "1975-12-28", "date_notif": "2006-06-19", "note": "Vitae dolorem corporis impedit eligendi laborum quidem.", "created_at": "2019-03-11 09:49:23", "updated_at": "2019-03-11 09:49:23" } }
  • 我更新了帖子,以便阅读

标签: reactjs laravel api


【解决方案1】:

您可以从要编辑的保险的路线 ID 中获取。

然后遍历所有保险并与路线中的 ID 进行比较。

class EditInsurances extends Component {
  render() {
    const { insurances } = this.props;
    // get from url-route ID 
    const insuranceId = this.props.match.params.id;

    const insurance = insurances.map(insurance => insurance.id === insuranceId)

    return (
      <div>
        <p>Hello</p>
        {insurance}
      </div>
    );
  }
}

【讨论】:

  • 我明白了:Line 8: 'insurances' is not defined no-undef
  • 你应该从这样的道具保险中获得,对吧? const { 保险 } = this.props;
  • 我用 const { insurances } = this.props 更新了答案;立即尝试。
  • 你能不能也控制台记录 this.props.match.params.id;让我知道你得到了什么
  • 好的,我明白了。链接是问题,而不是我应该使用 现在我得到了我需要的 id,但显示是一样,只有你好
猜你喜欢
  • 2020-08-31
  • 2021-05-03
  • 2018-01-09
  • 2019-12-27
  • 1970-01-01
  • 2017-12-08
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多