使用 API link 检索最新数据

Retrieve the latest data by using API link

目标:
每次我按下按钮 'Test' 时,您总是需要使用 API link 从后端获取新数据。然后它应该显示在模态窗体上。

问题:
当我更改输入框中的文本或删除所有文本然后关闭模态然后再次单击按钮测试时。将显示我所做的最新更改。它不应该发生,因为您始终应该使用 API link.

从后端获取最新数据

问题:
当您总是按下按钮 'test' 时,代码应该如何始终使用 api link 检索数据?

Stackblitz:
https://stackblitz.com/edit/react-ts-byxk6x?file=index.tsx

谢谢!


index.tsx

import React, { FC, useState } from 'react';
import { render } from 'react-dom';
import './style.css';
import { TestModalForm } from './TestModalForm';

interface AppProps {}
interface AppState {
  name: string;
}

const App: FC<AppProps> = () => {
  return (
    <div>
      <button data-bs-toggle="modal" data-bs-target="#myModal">
        Test
      </button>
      <br />

      <TestModalForm />
    </div>
  );
};

render(<App />, document.getElementById('root'));

TestModalForm.tsx

import React, { useState } from 'react';

export const TestModalForm = () => {
  const [inputid, setInputid] = useState('');
  const [inputTitle, setInputTitle] = useState('');

  React.useEffect(() => {
    async function FetchData() {
      var data = await fetch(
        'https://jsonplaceholder.typicode.com/todos/1'
      ).then((res) => {
        return res.json();
      });
      setInputid(data.id);
      setInputTitle(data.title);
    }

    FetchData();
  }, []);

  const handleIdInput = (e: any) => {
    setInputid(e.target.value);
  };

  const handleTitleInput = (e: any) => {
    setInputTitle(e.target.value);
  };

  // Reset Input Field handler
  const resetInputField = () => {
    setInputid('');
    setInputTitle('');
  };

  return (
    <div>
      <div
        className="modal"
        id="myModal"
        data-bs-backdrop="static"
        data-bs-keyboard="false"
        tabIndex={-1}
        aria-labelledby="staticBackdropLabel"
        aria-hidden="true"
      >
        <div className="modal-dialog">
          <div className="modal-content">
            <div className="modal-header">
              <h4 className="modal-title">TEST</h4>
              <button
                type="button"
                className="btn-close btn-close-white"
                data-bs-dismiss="modal"
              ></button>
            </div>
            <div className="modal-body">
              <input
                type="text"
                className="form-control"
                placeholder="Id"
                value={inputid}
                onChange={handleIdInput}
              />
              <br />
              <input
                type="text"
                className="form-control"
                placeholder="Title"
                value={inputTitle}
                onChange={handleTitleInput}
              />
              <br />
              <button className="form-control" onClick={resetInputField}>
                Reset
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

A 简单的解决方案是向 App 组件引入一些状态,通过单击测试按钮更新,可以传递给 TestMOdalForm 用作 useEffect 依赖项。

async/await和Promise-chains混在一起也是anti-pattern。任选其一。

示例:

const App: FC<AppProps> = () => {
  const [id, setId] = useState(0);

  return (
    <div>
      <button
        data-bs-toggle="modal"
        data-bs-target="#myModal"
        onClick={() => setId((c) => c + 1)} // <-- update state upon click
      >
        Test
      </button>
      <br />

      <TestModalForm id={id} /> // <-- pass state as prop
    </div>
  );
};

...

const TestModalForm = ({ id }) => { // <-- destructure prop
  ...

  React.useEffect(() => {
    async function fetchData() {
      try {
        const response = await fetch(
          'https://jsonplaceholder.typicode.com/todos/1'
        );
        const data = await response.json();

        setInputid(data.id);
        setInputTitle(data.title);
      } catch(error) {
        // handle any fetch rejections or other thrown errors
      }
    }

    fetchData();
  }, [id]); // <-- pass prop as dependency

  ...

  return (
    ...
  );
};