首页 > 解决方案 > 状态更改后正确重新触发功能(React)

问题描述

(这里是 React/JS 新手!)

你好,

我有一个组件正在呈现有关报告的一些数据。其中一个字段是执行报告的时间。在我的 API 中 - 我有一个外键,所以页面上呈现的值是 id 号。由于我无法从 API 触发字符串表示 - 我决定在前端进行某种映射。想法是在组件中使用“getKey”函数来显示这个字符串表示:

import React, { useState } from "react";

const ReportElement = ({ report, setReportUpdated, reportingPeriods }) => {
  const getKey = (object, value) => {
    return Object.keys(object).find((key) => object[key] === value);
  };


  const reportForUpdated = () => {
    setReportUpdated(report);
    console.log(report);
  };

  return (
    <tr key={report.id}>
      <td>{report.report}</td>
      <td>{report.reporting_period}</td>
      <td>{report.executed}</td>
      <td>{getKey(reportingPeriods,report.executed_on)}</td>
      <td>{report.on_time}</td>
      <td>{report.issues}</td>
      <td> {report.issues_description}</td>
      <td>
        <button className="update-status" onClick={reportForUpdated}>
          UPDATE STATUS
        </button>
      </td>
    </tr>
  );
};

export default ReportElement;

我遇到的问题是映射仅在从 API 获取数据时才有效。<td>一旦我在报告中更改了状态-当所有其他元素都根据更改的状态进行更新时,我最终会变成空的。我必须再次获取数据才能显示正确的值(例如映射到 id=13 的“Business Day 13”)。

任何关于如何以正确方式触发此功能的想法(以便在状态更改后呈现适当的值)都将受到高度赞赏。

把我的头撞在墙上几天,并决定询问 Stack Overflow 社区。

干杯!

编辑:

  1. 我正在传递 getKey 函数的对象如下所示(登录 consol 后):
{"": ""
BD 1 April 2021: 46
BD 2 April 2021: 47
BD 3 April 2021: 48
BD 4 April 2021: 49
BD 5 April 2021: 50
BD 6 April 2021: 51
BD 7 April 2021: 52
BD 8 April 2021: 53
BD 9 April 2021: 54
}
  1. 我将 prop 传递给具有一些属性的函数,其中一个是 id。“报告”的状态在更新所有报告状态的不同组件中发生了变化:
import React, { useState, useEffect } from "react";
// creating a component by declaring a function and passing inside all relevant props for updating the statuses
const Update = ({
  reportUpdated,
  setReportUpdated,
  setReports,
  reports,
  reportingPeriods,
}) => {

  const selection = ["", "YES", "NO"];

  const updateDatabase = async (id) => {
    console.log(reportUpdated);

    const res = await fetch(
      `http://localhost:8000/api/report_tracker/status-update/${id}`,
    content-type
   POST
      {
        method: "POST",
        headers: {
          "Content-type": "application/json",
        },
        body: JSON.stringify(reportUpdated),
      }
    );

    setReports(
      reports.map((report) => (report.id === id ? reportUpdated : report))
    );

    setReportUpdated([]);
  };

编辑2:

示例 - 我从 API 获得 50 作为 report.executed_on。

所以符合下面的代码:

<td>{getKey(reportingPeriods,report.executed_on)}</td>

我想从我在 getKey 函数中创建的“映射”中获取“BD 5 April 2021”。

此时 - 我的表的所有行都在提取正确的字符串(所以 BD 5、BD 6 等)但是当其中一个被更新时(例如我将 report.executed_on 更改为 55) - ReportElement 组件中的所有数据都为他们处于状态,但这个 td 标签最终为空。我必须再次获取数据才能看到发生的变化(Python 后端已更新并且已经显示 55,因此 post 方法似乎正在工作。我在开发人员工具中看到状态已更新为 55 的组件也是如此,但仅此而已直到我再次触发从后端获取数据以显示时才可见)。

标签: javascriptreactjsobject

解决方案


使用 useEffect 在功能组件中获取数据

useEffect(() => {
console.log(yourProp)
}, [yourProp])

这样 useEffect 将监视 yourProp 道具的任何变化。使用空数组(在 useEffect 中)意味着 useEffect 只会在功能组件的第一次渲染中触发。这意味着它不会在任何道具更改中触发。


推荐阅读