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

React页面导航时因组件重渲染丢失表单提交数据问题排查

Hey Sachidananda, great question! Let's break down why your form and table data disappears when you navigate away and return, plus how to fix it.

Why Your Data Gets Wiped

The root issue here is component re-mounting. When you leave the page, your DocumentTable component unmounts—meaning React throws away its state. When you come back, it re-mounts, and your useState hook resets to the original empty docData array you defined. That's why all your previous entries are gone!

Fix 1: Persist Data with localStorage (Quick & Simple)

For a straightforward fix, we can save your table data to the browser's localStorage whenever it updates, then load it back when the component initializes. Here's your modified code:

const DocumentTable=()=> {
  // Load saved data from localStorage, or use default if none exists
  const initialDocData = JSON.parse(localStorage.getItem('documentData')) || [{ id: "", name: "", code: "" }];
  const [documentData, setDocumentData] = useState(initialDocData);

  const tableRows = documentData.map((info) => {
    return (
      <Tr key={info.id}> {/* Added unique key for React list rendering! */}
        <Td>{info.id}</Td>
        <Td>{info.name}</Td>
        <Td>{info.code}</Td>
      </Tr>
    );
  });

  const addRows = (data) => {
    const totalDocuments = documentData.length;
    data.id = totalDocuments;
    const updatedDocumentData = [...documentData, data];
    setDocumentData(updatedDocumentData);
    // Save the new state to localStorage
    localStorage.setItem('documentData', JSON.stringify(updatedDocumentData));
  };

  // Optional: If you want to clear data when the component unmounts (remove if you want persistence across sessions)
  useEffect(() => {
    return () => {
      // localStorage.removeItem('documentData');
    };
  }, []);

  return (
    <Box>
      <DocumentForm func={addRows} />
      <TableContainer mt={'20'}>
        <Table variant="striped" colorScheme="teal" size='lg'>
          <Thead>
            <Tr>
              <Th>Document ID</Th>
              <Th>Document Name</Th>
              <Th>Document Code</Th>
            </Tr>
          </Thead>
          <Tbody>{tableRows}</Tbody>
        </Table>
      </TableContainer>
    </Box>
  );
}
export default DocumentTable;

Key Changes Here:

  • We initialize useState with data from localStorage (falling back to your original empty array if nothing is saved).
  • Every time we add a new row, we save the updated documentData to localStorage.
  • Added a key prop to the <Tr> element—this is required for React to efficiently render lists and avoid warnings.

Fix 2: Global State Management (For Larger Apps)

If your app is more complex and you need to share this document data across multiple components, use a global state solution like React Context API or Redux. This keeps your data outside of individual components, so it doesn't reset when components mount/unmount.

For example, with React Context:

  1. Create a context to hold your document state and update functions.
  2. Wrap your app (or the relevant section) with the context provider.
  3. Access and update the state from any component using useContext.

Quick Tips

  • localStorage is perfect for simple, single-component persistence—it keeps data even if the user closes and reopens the tab.
  • Global state is better for shared data across your app, like if you need to access these documents in another page or component.
  • Be mindful of localStorage limits (it can store ~5MB of data) and avoid saving sensitive information there.

内容的提问来源于stack exchange,提问作者Sachidananda MG

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 22:07:27