【问题标题】:React List Component does not rerender new listReact List 组件不会重新渲染新列表
【发布时间】:2020-03-07 21:42:51
【问题描述】:

我正在开发 Spotify 克隆,目前正在使用搜索功能。我已经设置了向 Spotify API 发送请求然后返回与该搜索结果一起弹出的艺术家、曲目和专辑列表的方法,因此我想将列表呈现为迷你组件并使列表重新呈现当您更改搜索结果并获得具有不同结果的新回调时。

<ArtistList items={this.state.artists} />

class ArtistList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            list: []
        }
    }
    componentDidMount() {
        this.setState({
            list: this.props.items
        });
    }

    componentWillReceiveProps(nextProps) {
        this.setState({
            list: nextProps.items
        });
    }
    render() {
        return (
            <div>
                <ul>
                    {this.state.list.map(item => (
                        <MiniArtist data={item}/>))}
                </ul>
            </div>
            );
    }
}

这是我为列表制作的代码,其中新项目将作为道具从搜索栏传入,然后更改状态,但这不会改变我在之后制作的 MiniArtist 组件中显示的内容第一次回调。有什么办法可以解决这个问题,使其随着搜索的变化而动态变化,就像在某些当前应用程序中一样,或者它是否过于明智,我应该创建一个单独的页面,从搜索结果中呈现组件一次并且需要重新加载每次。

【问题讨论】:

  • 一个。映射时应始终使用键。二。你为什么使用 state 而不仅仅是 props 中的项目???

标签: javascript reactjs state spotify


【解决方案1】:

尝试在&lt;MiniArtist /&gt; 组件中使用key={...}。并确保将 unique 指定为键。 (例如 ID)

<MiniArtist key={item.id} data={item} />

它的作用,基本上是告诉 React 列表中哪些项目已经改变,哪些是相同的。

【讨论】:

    猜你喜欢
    • 2023-03-13
    • 2023-03-28
    • 1970-01-01
    • 2022-11-29
    • 2016-05-09
    • 2020-02-13
    • 2021-05-19
    • 2022-01-26
    • 2019-12-08
    相关资源
    最近更新 更多