在 React 中获取箭头函数语法错误

Getting an arrow function syntax error in React

我有以下渲染 React 应用程序的代码。

import React from 'react';
import ReactDOM from 'react-dom';
import SearchBar from './components/search_bar';
import YTSearch from 'youtube-api-search';
import VideoList from './components/video_list'

const API_KEY = 'AIzaSyCF7K58Xwpr7m5C0yGy8Bck02iQ0fJ2yuI';


class App extends React.Component {

  constructor(props){

    super(props);

    this.state = {videos: []};

    this.YTSearch = this.YTSearch.bind(this);
  }

  YTSearch({key: API_KEY, term: BMW}, (videos => {
    this.setState({ videos });
  });
);

  render() {
    return (
      <div>
        <SearchBar />
        <VideoList videos={ this.state.videos }/>
      </div>
    );
  }
}


ReactDOM.render(<App />, document.querySelector('.container'));

我还认为我在使用 setState 函数时遇到了一些语法问题。

你的解构 setState 很好,你有一个括号 (open 需要关闭或者你可以删除它,因为你的箭头函数中只有一个参数。

Class 主体用于定义函数和变量,但您在 class 主体内调用函数 YTSearch,这会导致语法错误。如果你想调用该函数,那么要么在构造函数中调用它,要么在任何其他函数(如 componentDidMount 等)中调用它

constructor(props){
    super(props);
    this.state = {videos: []};
  }

componentDidMount(){
   // Call it here inside componentDidMount or any other function
    YTSearch({key: API_KEY, term: BMW}, (videos => {
      this.setState({ videos });
    }));
}

您的问题中没有明确说明您的具体问题,但通过查看您的代码,我认为您的 YTSearch 永远不会触发,因此您的状态永远不会设置视频列表。

如果您正在尝试创建一个方法来传递给触发搜索的搜索栏,或许可以试试这样的方法。希望对您有所帮助!

import React from 'react';
import ReactDOM from 'react-dom';
import SearchBar from './components/search_bar';
import YTSearch from 'youtube-api-search';
import VideoList from './components/video_list';

const API_KEY = 'AIzaSyCF7K58Xwpr7m5C0yGy8Bck02iQ0fJ2yuI';

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = { videos: [] };

    this.search = this.search.bind(this);
  }

  search(phrase) {
    YTSearch({ key: API_KEY, term: phrase }, videos => {
      this.setState({ videos });
    });
  }

  render() {
    return (
      <div>
        <SearchBar onSearch={this.search}/>
        <VideoList videos={this.state.videos} />
      </div>
    );
  }
}

ReactDOM.render(<App />, document.querySelector('.container'));