【问题标题】:When mapping over an array to generate React components, array order is not respected映射数组以生成 React 组件时,不遵守数组顺序
【发布时间】:2019-06-13 18:51:22
【问题描述】:

我有一个图像 src (this.props.images) 数组,用于在使用 Gatsby 制作的项目中渲染网格。这在本地运行时按预期工作 - 图像按照它们在数组中出现的顺序呈现。但是,我为 Netlify 构建并部署了一个版本,发现图像以随机顺序呈现,与原始数组的顺序不匹配。

任何想法可能导致这种行为?代码如下:

const Grid = styled.div`
    display: grid;
    grid-template-columns: repeat(4, 100px);
    grid-gap: 5px;
    grid-auto-rows: minMax(100px, auto);
`

export default class Board extends React.Component {
    render() {
        return (
            <Grid>
                {this.props.images.map((image, index) => (
                    <Image key={index} src={image}>
                    </Image>
                ))}
            </Grid>
        )
    }
}

【问题讨论】:

  • 尝试从 React 开发者工具中调试,检查这个组件(Board)是否按预期接收到数组。所以,不管它出现在那里,数组应该是这样的。没有其他办法。您可以从反应开发工具检查数组。

标签: reactjs gatsby


【解决方案1】:

这可能是因为您使用索引作为键。

您可以尝试使用两个库来生成唯一 ID:uuid 或 uniqid

npm install uniqid

import uniqueid from 'uniqid'

<Grid>{list.map((item) => <li key={uniqueid()}>{item}</li>)}</Grid>

【讨论】:

  • 谢谢!我现在已经使键独一无二,这通常似乎是更好的做法 - 但我认为它不会在这种情况下产生影响,因为我没有更改顺序/添加/删除任何组件?无论如何,问题仍然存在! :-)
【解决方案2】:

看起来 local 和 Netlify 都有不同的默认排序,那么给函数提供你想要的排序怎么样? 下面应该强制数组中项目的顺序。

{this.props.images.map((image, index) => (
    <Image key={index} src={image}>
    </Image>)).sort(() => a - b )
  }
</Grid>

【讨论】:

  • local and Netlify each have different default sorts。嗯?
  • 谢谢!现在已经意识到 React 组件实际上是按预期的正确顺序生成的,但是 src 属性的值在某种程度上没有正确过滤(在上面添加了更多信息)...
猜你喜欢
  • 1970-01-01
  • 2019-08-14
  • 1970-01-01
  • 2021-04-22
  • 1970-01-01
  • 1970-01-01
  • 2022-10-06
  • 2020-09-25
  • 2018-06-16
相关资源
最近更新 更多