React:如何在 CRUD 应用程序中设置编辑功能以在保持 id 的同时切换出整个组件

React: How to set up Edit Function in CRUD app to switch out whole components while keeping id

大家好,我是 React 的新手,我 运行 有点困惑。 我正在制作一个简单的 CRUD 网站创建器,我已经创建了添加和删除功能,它们工作得很好!但我在使用编辑功能时遇到了问题。

我基于使用字符串数据类型的本教程 https://www.digitalocean.com/community/tutorials/react-crud-context-hooks

所以在我看来,这就是它应该的工作方式

我已经使用状态来传递具有几个属性的对象

const [selectedSection, setSelectedSection] = useState({
id: null,
section: {},

});

我已将 id 设置为我正在编辑的当前组件

const currentSectionId = route.match.params.id;

在我的 useEffect 中,我在设置新组件的同时跳过了当前部分中的 id

  useEffect(() => {
const sectionId = currentSectionId;
const selectedSection = sections.find(
  (currentSectionTraversal) => currentSectionTraversal.id === parseInt(sectionId)
);
    setSelectedSection(selectedSection);},[currentSectionId, sections]);

  const onSubmit = (e) => {
    e.preventDefault();
    editSection(selectedSection);
    history.push("/");
    console.log("selectedSection id",selectedSection.section, selectedSection.id)
  };

按钮函数用于展开 selectedSection 并更改按钮中唯一请求的值。

const handleOnChange = (userKey, newValue) => setSelectedSection({ ...selectedSection, [userKey]: newValue });

在我的渲染代码中,我将按钮设置为

<button href="/" className="bg-green-400 w-mt hover:bg-green-500 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"                
                  value={selectedSection.section}
                  onChange={() => handleOnChange("section", QuickLinks)}
                  
                  type="submit"
                  >Add Section</button>

现在我尝试了不同的方法,比如更改 useState 对象中的数据类型,使用 setSelectedSection 来更改 SelectedSection.section 但在控制台中,我注意到按钮没有传送数据。

我已经将我的组件导入为 Quicklinks,但我不确定为什么它没有将组件传递到 selectedSection.section

这里是 editSection 的全部代码

import React, { useState, useContext, useEffect} from "react";
import { useHistory, Link } from "react-router-dom";

import { GlobalContext } from "./GlobalState";

import QuickLinks from '../components/sections/quick_links/quickLinks';
import QuickLinksPreview from './images/quick-link.jpg';

export const EditSection = (route) => {
  let history = useHistory();

  const { sections, editSection } = useContext(GlobalContext);

  const [selectedSection, setSelectedSection] = useState({
    id: null,
    section: {},
  });

  const currentSectionId = route.match.params.id;

  useEffect(() => {
    const sectionId = currentSectionId;
    const selectedSection = sections.find(
      (currentSectionTraversal) => currentSectionTraversal.id === parseInt(sectionId)
    );
    setSelectedSection(selectedSection);
  }, [currentSectionId, sections]);

  const onSubmit = (e) => {
    e.preventDefault();
    editSection(selectedSection);
    history.push("/");
    console.log("selectedSection id",selectedSection.section, selectedSection.id)
  };

  const handleOnChange = (userKey, newValue) => setSelectedSection({ ...selectedSection, [userKey]: newValue });

  if (!selectedSection || !selectedSection.id) {
    return <div>Invalid Employee ID.</div>;
  }
    
    return (
        <React.Fragment>
          
          <div className="w-full container mt-20 mx-auto">
            <form onSubmit={onSubmit}>

              <table>
                <tbody>
                {/* ----------------------------Item List Start COPY------------------------ */}          
                  <tr>
                    <td className="px-6 py-4 whitespace-nowrap">

                      <div className="flex items-center">

                        <div className="flex-shrink-0 h-40 w-50 shadow">
                          <img className="h-40 w-full " src={QuickLinksPreview} alt="" />
                        </div>

                      </div>

                    </td>

                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="text-sm text-gray-900">Quick Links</div>
                      <div className="text-sm text-gray-500">Multi Card Quick Links<br></br>for Description and links</div>
                    </td>

                    <td className="px-6 py-4 whitespace-nowrap">
                        <span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-blue-100 text-white-800"> Beta </span>
                        {/* Component Development Status
                          <span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-red-100 text-black-800"> Constrution </span>
                        <span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800"> Active </span>
                        <span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-yellow-100 text-black-800"> Testing </span>
                        */}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">S03-S5</td>
                      {/* Pricing Levels as Structure
                            S = Labels that it is sections
                            02 = is the Template Id for Developers
                            S = Standard Price
                            3 = Price level
                      */}
                    <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                    <button href="/" className="bg-green-400 w-mt hover:bg-green-500 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"                
                      value={selectedSection.section}
                      onChange={() => handleOnChange("section", QuickLinks)}
                      
                      type="submit"
                      >Add Section</button>
                      
                    </td>
                  </tr>
                  {console.log("Selected section", selectedSection.section)}
                  {/* ----------------------------Item List END COPY------------------------ */}       
                </tbody>
              </table>

              <div className="flex items-center justify-between">  
                <div className="block mt-5 bg-red-400 w-full hover:bg-red-500 text-white font-bold py-2 px-4 rounded focus:text-gray-600 focus:shadow-outline">
                  <Link to="/">Cancel</Link>
                </div>
              </div>

            </form>
          </div>
        </React.Fragment>
      );
};

尝试使用 onClick 而不是 onChange 作为按钮。我认为 onChange 用于 <input> 标签而不是按钮。另外 href 用于链接,而不是按钮。除非此按钮采用 type=submit 形式,否则没有必要。 onClick 也不需要箭头函数。 onChange={() => handleOnChange("section", QuickLinks)} -> onClick={handleOnChange("section", QuickLinks)}.