You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何仅显示表单的最新提交数据?

问题:React表单提交后仅展示最新提交数据的实现问题

我在React项目的页面中设有一个表单,希望在表单下方仅展示最新的表单提交数据,但当前会显示截至目前的所有提交记录。尝试过使用data filter、条件判断等方法,但因参数设置问题持续报错,不知如何解决。


Form组件代码

export default function TourneyForm() {
  const [hallname, setHallName] = useState("");
  const [name, setName] = useState("");
  const [matricnumber, setMatricNumber] = useState("");
  const [players, setPlayers] = useState(0);
  const [sport, setSport] = useState("");
  const [brackettype, setBracketType] = useState("");
  const handleSubmit = (e: any) => {
    e.preventDefault();
    axios
      .post(TOURNEY_URL, {
        hallname: hallname,
        name: name,
        matricnumber: matricnumber,
        players: players,
        sport: sport,
        brackettype: brackettype,
      })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
    setHallName('')
    setName('')
    setMatricNumber('')
    setPlayers(0)
    setSport('')
    setBracketType('')
  };
  return (
    <>
      <form onSubmit={handleSubmit}>
        <div className="form-group row py-4">
          <div className="col"></div>
          <label className="col-1" htmlFor="hallname">
            Hall Name
          </label>
          <div className="col-3">
            <select
              className="custom-select"
              id="hallname"
              value={hallname}
              onChange={(e) => setHallName(e.target.value)}
            >
              <option selected>Name of Hall/RC</option>
              <option value="Temasek Hall">Temasek Hall</option>
              <option value="Eusoff Hall">Eusoff Hall</option>
              <option value="KEVII Hall">KEVII Hall</option>
              <option value="Kent Ridge Hall">Kent Ridge Hall</option>
              <option value="Sheares Hall">Sheares Hall</option>
            </select>
          </div>
          <div className="col"></div>
        </div>
      </form>
    </>
  );
}

调用页面代码

export default function CreateTourney() {
  const[data, setData] = useState([])
  axios.get(url)
  .then (function (response) {
    setData(response.data)
  });
  return (
    <>
      <NavBar />
      <div className="row">
        <div className="col"></div>
        <span className="col-5 text-center fs-5 py-3">
          Fill in and submit this form to create a new tournament bracket! Click "See all tournaments" to find
          your newly created tournament.
          <br /><br />
          Note: One student number can only be registered for one tournament.
        </span>
        <div className="col"></div>
        <hr />
      </div>
      <TourneyForm />
      
      {data.filter(element.data == )}
        {data.map((element) => <TourneyIndivListing data={element} />)}
      
    </>
    
  )
}

解决方案

方法1:直接存储最新提交数据(推荐)

不需要拉取全部历史数据,在表单提交成功后直接把最新数据传递给父组件存储:

  1. 在CreateTourney组件新增状态存储最新提交:
const [latestSubmission, setLatestSubmission] = useState(null);
  1. 修改TourneyForm组件,通过props接收提交成功后的回调:
export default function TourneyForm({ onSubmitSuccess }) {
  // 原有代码不变
  const handleSubmit = (e: any) => {
    e.preventDefault();
    axios
      .post(TOURNEY_URL, {
        hallname: hallname,
        name: name,
        matricnumber: matricnumber,
        players: players,
        sport: sport,
        brackettype: brackettype,
      })
      .then(function (response) {
        console.log(response);
        // 提交成功后把最新数据传给父组件
        if (onSubmitSuccess) {
          onSubmitSuccess(response.data);
        }
      })
      .catch(function (error) {
        console.log(error);
      });
    // 清空表单代码不变
  };
  // 原有返回代码不变
}
  1. 在CreateTourney中调用TourneyForm时传入回调,并渲染最新数据:
<TourneyForm onSubmitSuccess={(newData) => setLatestSubmission(newData)} />

// 替换原有错误的filter和map代码
{latestSubmission && <TourneyIndivListing data={latestSubmission} />}

方法2:从全量数据中筛选最新条目

如果必须保留拉取全量数据的逻辑,可通过数据中的排序字段(如创建时间、自增ID)筛选最新一条:

  1. 确保后端返回的每条数据包含排序依据(比如createdAt时间戳或id自增字段)
  2. 在CreateTourney中处理数据:
// 按创建时间倒序排序后取第一条
const latestItem = data.length > 0 
  ? [...data].sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))[0] 
  : null;

// 或按自增ID倒序排序取第一条
// const latestItem = data.length > 0 ? [...data].sort((a, b) => b.id - a.id)[0] : null;
  1. 仅渲染最新条目:
{latestItem && <TourneyIndivListing data={latestItem} />}

额外修复点

  • CreateTourney中的axios.get需放在useEffect中,避免组件重复渲染时发起重复请求:
import { useEffect } from 'react';

export default function CreateTourney() {
  const[data, setData] = useState([])
  
  useEffect(() => {
    axios.get(url)
      .then (function (response) {
        setData(response.data)
      });
  }, []); // 空依赖数组确保仅在组件挂载时请求一次
  
  // 其他代码不变
}
  • 原代码中{data.filter(element.data == )}是语法错误,filter需要传入返回布尔值的函数,这也是报错原因之一。

内容的提问来源于stack exchange,提问作者yeoyao yoyo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 15:44:54