我正在撰寫一個 react 應用程式,其中用戶可以點擊一個按鈕,將陣列中的一個專案與它左邊的專案進行交換。我撰寫了一個函式來實作這一點,而不改變頁面上正在呈現的原始專案陣列,但是這個函式沒有對我的代碼做任何事情,也沒有回傳任何錯誤。
以下是我的應用程式組件,它定義了 swapLeft 函式,然后將該函式作為道具傳遞給 Item 組件:
我的應用程式組件定義了 swapLeft 函式。
import React, { useState } from "react"。
import Form from "./components/Form"/span>。
import Item from "./components/Item">;
import { nanoid } from "nanoid" ;
import ' ./App.css';
function App(props) {
const [items, setItems] = useState(props.items)。
function deleteItem(id) {
const remainingItems = items.filter(item => id !== item.id) 。
setItems(reservedItems)。
}
function swapLeft(index){
const index2 = index - 1;
const newItems = items.slice()。
newItems[index] = items[index2];
newItems[index2] = items[index];
return newItems;
}
const itemList = items
.map((item, index) => (
< Item
id={item.id}。
index={index}
name={item.name}
key={item.id}
deleteItem={deleteItem}。
swapLeft={swapLeft}。
/>
));
function addItem(name) {
const newItem = { id: "item-" nanoid(), name: name };
setItems([...items, newItem]) 。
}
return (
<div className="form"/span>>
<Form addItem={addItem} />
<ul className="names">
{專案串列}
</ul> {itemList}
</div>/span>
);
}
export default App;
而專案組件:
import React from "react";
import { Button, Card, CardContent, CardHeader } from'semantic-ui-react'
export default function Item(props) {
return (
<Card>
<CardContent>/span>
<CardHeader>/span> {props.name}</CardHeader>
<Button onClick={() => props.deleteItem(props.id)}>
洗掉<span className="visually-hidden"> {props. name}</span> {props.
</Button>/span>
</CardContent>/span>
<CardContent style={{ display。 'flex' }}>
< i className="arrow left icon" onClick={() => props. swapLeft(props.index)} style={{ color: 'blue'}></i>
< i className="右箭頭圖示" style={{/span> color: 'blue'}}></i>/span>
</CardContent>/span>
</Card>
);
}
是否有更好的方法讓我寫這個函式并實作它?我想我可以用React的setState鉤子做一些事情,但這似乎是一個更簡單的解決方案。我是React的新手,所以任何見解都是有幫助的
。uj5u.com熱心網友回復:
React知道狀態是否改變的方法是狀態是否指向記憶體中一個完全不同的地址。就陣列而言,如果你希望React因為狀態中的陣列發生了變化而重新渲染頁面,你需要為它提供一個全新的陣列。修改現有的陣列將不會觸發渲染程序。
基本來說,你需要做的是將swapLeft函式的最后一行改為
setItems(newItems)
如果你想讓變化立即生效(我猜你在這里想做的就是這個)
你也可以使用該函式的回傳值并在另一個組件中改變狀態,僅供參考。編輯:
我又看了一遍,你對 swap 的實作也是錯誤的,但即使你糾正了它,你仍然看不到變化,除非你做了我上面提到的事情
完整正確的函式應該是 function swapLeft(index) {
const index2 = index - 1;
const newItems = items.slice()。
const temp = items[index];
newItems[index] = items[index2];
newItems[index2] = temp;
setItems(newItems)。
uj5u.com熱心網友回復:
也許只是為了澄清前面的問題。如果你不呼叫setState,你的組件就不會重新渲染。這意味著無論你對這些陣列做什么,都不會在螢屏上看到。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/326331.html
標籤:
