簡體   English   中英

刪除一個組件后,React 列表組件不會重新渲染

[英]React list component won't rerender after deleting one component from it

我正在用 React 編寫一種 ToDo 應用程序,其中包含板、列表和卡片作為組件。 我正在使用 API 對這些組件進行操作。 Board 有一個 List 組件列表,List 組件有一個 Card 組件列表。

Board 過濾列表組件列表,僅顯示設置為打開的組件。 當我嘗試從董事會關閉列表時,董事會以某種方式重新渲染以僅刪除最后一個列表組件。 我已經通過 Postman 檢查它並且正確的列表被關閉,但我無法讓它正確渲染。 刷新頁面后,Board 組件正確渲染,List 組件按預期顯示。

下面是我的代碼示例。

//List component
 const archiveList = () => {
    fetch(
      `https://URL/${
        props.list.id
      }/closed?key=${API_KEY}&token=${TOKEN}&value=${true}`,
      {
        method: "PUT",
      }
    )
      .then((response) => response.json())
      .then(props.setLists(props.lists.filter((list) => list.id !== props.list.id)))
  };

//Board component

const [lists, setLists] = useState([]);
const { selectedBoard } = useContext(BoardContext);


useEffect(() => {
    fetch(
      `https://URL/${getBoardId()}/lists?key=${API_KEY}&token=${TOKEN}`
    )
      .then((response) => response.json())
      .then((data) => setLists(data.filter((d) => d.closed === false)));
  }, [selectedBoard]);

const displayLists = () => {
    return lists.map((list, i) => {
      return (
        <Cell key={i} col={12} shadow={1}>
          {list.idBoard === getBoardId() ? ( <div>
            <List list={list} setLists={setLists} lists={lists} />
           </div>
          ) : (
            <div></div>
          )}
        </Cell>
      );
    });
  };

我還是 React 的新手,所以這讓我很困惑。 任何幫助是極大的贊賞!

在獲取數據並將其轉換為 json 之后,在最后一次回調中,您的 List 組件中似乎存在問題。

const archiveList = () => {
fetch(
  `https://URL/${
    props.list.id
  }/closed?key=${API_KEY}&token=${TOKEN}&value=${true}`,
  {
    method: "PUT",
  }
)
  .then((response) => response.json())
  // **** Please check the line below ****
  .then(props.setLists(props.lists.filter((list) => list.id !== props.list.id)))
  // **** It should have been like this **** 
  // .then(data => doSomethingWith(data))
};
 // Use the data from fetch in the next callback

暫無
暫無

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

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