簡體   English   中英

如何使用按鈕單擊中的數據從子組件到父組件觸發 setState 函數

[英]How to fire a setState function in react from child componenet to parent componenet with data from a button click

我有一個名為 FormLeadBuilderEdit 的父組件,它是 useState 鈎子,我將 setState(在我的情況下為 setCards)函數傳遞給我的名為 Card 的子組件。 出於某種原因,當我調用 setCard("vale") 時,子組件中的狀態不會更新。 所以我不確定我做錯了什么。

任何幫助都會很棒

謝謝

FormLeadBuilderEdit 組件

import React, { useState, useEffect } from "react";
import { Card } from "./Card";

const FormLeadBuilderEdit = ({ params }) => {

  const inputs = [
    {
      inputType: "shortText",
      uniId: Random.id(),
      label: "First Name:",
      value: "Kanye",
    },
    {
      inputType: "phoneNumber",
      uniId: Random.id(),
      label: "Cell Phone Number",
      value: "2813348004",
    },
    {
      inputType: "email",
      uniId: Random.id(),
      label: "Work Email",
      value: "kanye@usa.gov",
    },
    {
      inputType: "address",
      uniId: Random.id(),
      label: "Home Address",
      value: "123 White House Avenue",
    },
    {
      inputType: "multipleChoice",
      uniId: Random.id(),
      label: "Preferred Method of Contact",
      value: "2813348004",
      multipleChoice: {
        uniId: Random.id(),
        options: [
          {
            uniId: Random.id(),
            label: "Email",
            checked: false,
          },
          {
            uniId: Random.id(),
            label: "Cell Phone",
            checked: false,
          },
        ],
      },
    },
    {
      inputType: "dropDown",
      uniId: Random.id(),
      label: "How did you find us?",
      value: "2813348004",
      dropDown: {
        uniId: Random.id(),
        options: [
          {
            uniId: Random.id(),
            label: "Google",
          },
          {
            uniId: Random.id(),
            label: "Referral",
          },
        ],
      },
    },
  ];
  const [cards, setCards] = useState([]);

  setCards(inputs)

  return (
    <>
      <Card
        key={card.uniId + index}
        index={index}
        id={card.uniId}
        input={card}
        setCards={setCards}
        params={params}
        cards={cards}
      />
    </>
  );
};

export default FormLeadBuilderEdit;

購物車組件

import React, { useRef } from "react";
import { Random } from "meteor/random";

export const Card = ({ setCards, cards }) => {
    const addOption = () => {
    const newCards = cards;

    newCards.map((card) => {
      if (card.inputType === "multipleChoice") {
        card.multipleChoice.options.push({
          uniId: Random.id(),
          label: "test",
          checked: false,
        });
      }
    });

    console.log(newCards);

    setCards(newCards);

  return (
    <>
      <button onClick={addOption} type="button">
        Add Option
      </button>
    </>
  );
};

正如其中一位用戶所指出的,您正在傳遞一個空的cards數組,您正在該數組上執行map操作,這並不奇怪,它本身返回一個空數組,因此您沒有得到任何狀態更改。

傳遞setCards的邏輯是正確的。

這是一個小示例,其中正在發生並顯示狀態更改。


import React, { useState } from "react";

const App = () => {
  const [cards, setCards] = useState([]);

  return (
    <>
      <Card
        setCards={setCards}
        cards={cards}
      />
      <p>{cards.toString()}</p>
    </>
  );
};



const Card = ({ setCards, cards }) => {
  const addOption = () => {
    setCards(["1","2"]);
  };

  return (
    <>
      <button onClick={addOption} type="button">
        Add Option
      </button>
    </>
  );
};

export default App;

截屏:

從子組件更改狀態

代碼沙盒鏈接

React 使用變量引用來了解哪個狀態已更改,然后觸發重新渲染。

所以你想知道的關於狀態的第一件事就是“不要直接改變狀態”。
參考: https : //reactjs.org/docs/state-and-lifecycle.html#using-state-correctly

相反,生成一個包含更改的新狀態(具有不同的變量引用):

const addOption = () => {
    const newCards = cards.map((card) => {
      if (card.inputType === "multipleChoice") {          
        const newOption = {
          uniId: Random.id(),
          label: "test",
          checked: false,
        };
        card.multipleChoice.options = [...card.multipleChoice.options, newOption];
      }
      return card;
    });

    setCards(newCards);
    // setCards(cards); <- this refer to the current `cards` which will not trigger re-render
  };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM