【问题标题】:React not rendering properly反应没有正确渲染
【发布时间】:2021-07-22 04:51:21
【问题描述】:

当更改我的 id (/movie/:id) 时,我正在重新渲染我的整个组件。有时我必须点击我喜欢的 3 或 4 次才能进行更改,有时我只需点击一次(但我落后一个组件)。 这是我的代码:

import React from "react";
import "../styles/DetailFilm.css"
import {Link} from 'react-router-dom';
const API_IMAGES = 'https://image.tmdb.org/t/p/w500';


class DetailFilm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
                    id: props.movie_id,
            info: {},
            recommandation: []
        }
    }
    componentDidMount() {
        const fetchData = async () => {
            //fetch api
            this.setState({info: data,recommandation:data_recommandation_spliced })
        }
        fetchData();
        

    }
    componentWillReceiveProps(nextProps) {
        console.log("RENDERING" + nextProps.movie_id)
        const fetchData = async () => {
            // fetch api

            this.setState({id: nextProps.movie_id,info: data,recommandation:data_recommandation_spliced })
            console.log("Rendered" + nextProps.movie_id)
        }
        fetchData();
    }
    render()  {
        return (
            //css
                    {this.state.recommandation.map((movie) => 
                        <Link to={`/movie/${movie.id}`}>
                            <img src = {API_IMAGES + movie.poster_path} className="image-movie-genre"/>
                        </Link>
                    )}
        )
    }

}
export default DetailFilm;

感谢您的帮助!

【问题讨论】:

  • 触发点赞动作的逻辑在哪里?
  • 有类似的动作。我正在从一个电影页面切换到另一个页面。动作结束

标签: javascript reactjs react-router react-component


【解决方案1】:

从数组中添加 JSX 元素时,每个元素都需要一个唯一的 key 属性,以便 React 可以跟踪 DOM 中的必要更改。您需要向 Link 元素添加键,以便 React 知道更新它们。

【讨论】:

  • 感谢您的回答。我糊涂了。我应该在我的链接中添加像 key = {id} 吗?
  • 感谢您的文档。我现在明白拥有钥匙的重要性。不幸的是,仍然无法正常工作:(
【解决方案2】:

我找到了一个不是我一开始想要的解决方案。 我从使用 Class 更改为使用 useEffect avec id 作为参数的函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多