我正在使用Gatsby,所以像大多数Gatsby应用一样,我正在使用graphql
获取一个数组,然后将edges/nodes
(即项数组)通过props
传递给所有各种children/grandchildren/
等。
但是,我希望用户能够单击随机播放按钮并随机播放此array
。在this SO answer seems to use props as initial state.中给出的答案我认为这是anti-pattern。
但是我看不到另一种方法...
所以在我的 index.js
let items = this.props.data.allItem.edges
这些items
被传递给子组件。
按钮如何对它们进行排序并提示重新渲染(通过setState
)?
答案 0 :(得分:0)
您发送的有关反模式的链接清楚地表明,在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会自动使用更新后的数据重新渲染您的组件。