[英]Why to use Object.assign() to update functional component props change?
我有一個學生名單,我把他們展示在桌子上。 有兩個按鈕指示我應該按哪個值對列表進行排序(姓名或出生日期)。 當單擊按鈕並對列表進行排序時,列表本身正在排序,但如果我不使用Object.assign(newList, oldList)
將列表分配給新列表,它不會更新,然后通過傳遞給它來更新它更新 state function updateList(newList)
。 這是我的代碼:
const students= [
{
name: "John Done",
year: 1,
birthdate: "2020-01-24",
},
{
name: "Another Done",
year: 3,
birthdate: "2002-02-20",
},
{
name: "Jack London",
year: 2,
birthdate: "1800-01-04",
},
{
name: "Text Name",
year: 3,
birthdate: "1990-02-24",
},
{
name: "Name",
year: 2,
birthdate: "2005-04-01",
},
];
ReactDOM.render(<App students={students} />, document.getElementById('root'));
function App({ students }) {
const [studentsList, setStudentsList] = useState(students);
const sortByYear = () => {
// let sortedstudents = [];
// Object.assign(sortedStudents, studentsList);
// sorteStudents.sort((a, b) => b.year - a.year);
// console.log(sorteStudents);
// setStudentsList(sortedStudents);
studentsList.sort((a,b) => b.year - a.year));
setStudentsList(studentsList);
};
const sortByDates = () => {
// let sortedStudents = [];
// Object.assign(sortedStudents, studentsList);
// sortedStudents.sort((a, b) => new Date(b.birthdate) - new Date(a.birthdate));
// console.log(sortedStudents);
// setStudentsList(sortedStudents);
studentsList.sort((a, b) => new Date(b.birthdate) - new Date(a.birthdate));
setStudentsList(studentsList);
};
return (
<div className="App">
<div>
<label>
Sort By
</label>
<button
onClick={() => sortByYear()}
>
Year
</button>
<button
onClick={() => sortByDates()}
>
Most Old
</button>
</div>
<Students students={studentsList} />
</div>
);
}
function Students({ students }) {
return (
<div>
<table>
<thead>
<tr>
<th>Name</th>
<th>Year</th>
<th>Date of birth</th>
</tr>
</thead>
<tbody>
{students.map((student, index) => (
<tr key={index}>
<td>{student.name}</td>
<td>{student.year.toString()}</td>
<td>{student.birthdate}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
因此,即使學生的列表正在排序,state 也不會更新,但是如果我將初始列表分配給新列表,然后對其進行排序,然后更新 state 它正在工作。
let sortedStudents = [];
Object.assign(sortedStudents, studentsList);
sortedStudents.sort((a, b) => new Date(b.birthdate) - new Date(a.birthdate));
//console.log(sortedStudents);
setStudentsList(sortedStudents)
studentsList.sort((a, b) => new Date(b.birthdate) - new Date(a.birthdate));
setStudentsList(studentsList);
所以問題是為什么我需要將我的studentsList
分配給新數組,特別是使用Object.assign()
以便setStudentsList()
更新組件的 state? 我剛開始學習 React,所以這些狀態的實際工作方式讓我很困惑。
我發現的類似帖子
正如Brain提到的:React 確定是否應該重新渲染基於先前道具與下一個道具的相等性,以及先前 state 與下一個 state 的相等性。 通過改變原始的 state 數組,之前的 studentList 與更新的 studentList 具有引用相等性,並且 react 不會檢測到它需要重新渲染。
因此,為了更改列表並讓 React 檢測到更改,需要使用(變異)數組的值,而不是其引用。
正如Bergi暗示的那樣:按值復制數組的替代方案
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.