【问题标题】:How to shuffle an array of items in Gatsby without using props as initial state?如何在不使用道具作为初始状态的情况下对 Gatsby 中的一组项目进行洗牌?
【发布时间】:2019-12-06 01:26:29
【问题描述】:

我正在使用 Gatsby 和大多数 Gatsby 应用程序一样,我使用 graphql 获取一个数组,然后通过 propsedges/nodes(即项目数组)向下传递给所有各种 children/grandchildren/等等

但是,我希望用户能够单击随机播放按钮并随机播放此arraythis SO answer seems to use props as initial state.中给出的答案我以为这是anti-pattern

但我没有看到其他方法可以做到这一点......

所以在我的 index.js

let items = this.props.data.allItem.edges

这些items 被传递给子组件。

按钮如何对它们进行排序并提示重新渲染(通过setState)?

【问题讨论】:

    标签: javascript reactjs graphql gatsby


    【解决方案1】:

    您发送的关于反模式的链接清楚地表明,在constructorgetInitialState 中使用道具作为状态是一种反模式。正确的做法是使用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 会自动用更新的数据重新渲染你的组件。

    【讨论】:

    • 但是如何通过单击按钮进行重新渲染和新排序?
    • @KylePennell 我刚刚更新了我的答案。基本上,您只需在每次单击按钮时重新排序状态数据,React 就会自动重新渲染。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    • 2022-01-15
    • 2016-07-14
    相关资源
    最近更新 更多