[英]How to shuffle an array of items in Gatsby without using props as initial state?
我正在使用 Gatsby,所以像大多數 Gatsby 應用程序一樣,我正在使用graphql
獲取一個數組,然后通過props
將edges/nodes
(即項目數組)向下傳遞給所有各種children/grandchildren/
等。
但是,我希望用戶能夠單擊隨機播放按鈕並隨機播放此array
。 這個 SO答案中給出的答案似乎使用道具作為初始狀態。 我認為這是一種反模式。
但我沒有看到另一種方法來做到這一點......
所以在我的index.js
let items = this.props.data.allItem.edges
這些items
被傳遞給子組件。
按鈕如何對它們進行排序並提示重新渲染(通過setState
)?
您發送的關於反模式的鏈接清楚地表明,在constructor
或getInitialState
使用 props 作為狀態是一種反模式。 正確的做法是使用getDerivedStateFromProps
:
https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops
// this example sets this.state.items as a sorted version of the array that comes from props
static getDerivedStateFromProps(props, state) {
return {
items: props.data.allItems.edges.sort() // you can sort here
};
}
這將確保您的狀態與道具更改同步。
下一步是在單擊按鈕時對項目進行排序。 單擊按鈕時運行的方法如下所示:
sortItems() {
this.setState(state => ({
items: state.items.sort()
}));
}
當狀態改變時,React 會自動用更新的數據重新渲染你的組件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.