gpt4 book ai didi

reactjs - 如何修复 React ' is not defined no-undef' ?

转载 作者:行者123 更新时间:2023-12-04 17:32:21 25 4
gpt4 key购买 nike

我正在尝试为电影列表中的每部电影创建详细 View 。我有 Django 作为后端,React 作为前端。

当我尝试为每部电影制作详细 View 时,出现错误。

错误日志:

Failed to compile.

./src/components/movie-list.js
Line 5:26: 'movie' is not defined no-undef
Line 6:28: 'movie' is not defined no-undef

Search for the keywords to learn more about each error.

我试图绑定(bind)但不完全理解问题出在哪里。

App.js
import React, { Component } from 'react';
import MovieList from "./components/movie-list";

componentDidMount() {
//fetch data
fetch('http://127.0.0.1:8000/api/movies/', {
method: 'GET',
headers: {
'Authorization': 'Token 8588cb6fcc2ee0bf9915d4c6b720554347d5883f'
}
}).then(resp => resp.json())
.then(res => this.setState({ movies: res }))
.catch(error => console.log(error))
}

movieClicked = movie => {
console.log(movie);
}

render() {
return (
<div className="App" >
<header className="App-header">
<h1>Movie Rater</h1>
<MovieList movies={this.state.movies} movieClicked={this.movieClicked}/>
<MovieDetails movie={this.state.selectedMovie}/>
</header>
</div>
);
}
}


电影列表.js
import React from 'react';

function MovieList(props) {

const movieClicked = movie = evt => {
props.movieClicked(movie);
}

return (
<div>
{props.movies.map(movie => {
return (
<h3 key={movie.id} onClick={movieClicked(movie)}>
{movie.title}
</h3>
)
})}
</div>
)
}

export default MovieList;

我想让详细 View 工作。

最佳答案

您指的是在方法 movieClicked 中超出范围的变量.将其更改为:

const movieClicked = (movie) => {
props.movieClicked(movie);
}

编辑:

正如评论中的一些人所指出的,简化的解决方案是:
import React from 'react';

function MovieList(props) {
return (
<div>
{props.movies.map(movie => {
return (
<h3 key={movie.id} onClick={() => props.movieClicked(movie)}>
{movie.title}
</h3>
)
})}
</div>
)
}

export default MovieList;

关于reactjs - 如何修复 React ' is not defined no-undef' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58352763/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com