为使用的变量编译警告no-unused-vars

时间:2018-06-01 09:38:56

标签: javascript reactjs

所以我有一个React组件,SearchBooks接收来自主books状态的数组App.js以及一个函数onUpdateBooksState,也来自{ {1}}。

一切正常但我收到的警告说没有被使用,但它们都是。

为什么我会收到这些警告?如何纠正潜在问题?

App.js

SearchBooks.js

编译器警告:

import React, { Component } from 'react' import * as BooksAPI from './utils/BooksAPI' import Book from './Book'; export default class SearchBooks extends Component { state = { query: '', results: [] } updateQuery(query) { this.setState(() => ({ results: [], query: query })) this.bookSearch(query) } bookSearch(e) { if (e.length > 0) BooksAPI.search(e) .then(searchResults => this.setState(currentState => ({ results: this.updateExistingShelves(searchResults) }))); } updateExistingShelves(searchResults) { if(searchResults.error !== "empty query") { const myBooks = this.props.books // books used here const addToState = searchResults.filter((result) => myBooks.find(b => { if(b.id === result.id) result.shelf = b.shelf return result })) myBooks.concat(addToState) return searchResults } } render() { const { query, results } = this.state const { onUpdateShelf, books, onUpdateBooksState } = this.props return( <div className="search-books"> <div className="search-books-bar"> <a className="close-search" >Close</a> <div className="search-books-input-wrapper"> <input type="text" placeholder="Search by title, author or subject" value={query} onChange={(event) => this.updateQuery(event.target.value)} /> </div> </div> <div className="search-books-results"> <ol className="books-grid"> <li> { results ? ( results.map((book) => ( <Book key={book.id} book={book} updateShelf={onUpdateShelf} // onUpdateShelf used here /> )) ) : ( <h4>No results for, "{query}"</h4> )} </li> </ol> </div> </div> ) } }

Chrome警告:

./src/SearchBooks.js
  Line 45:  'books' is assigned a value but never used               no-unused-vars
  Line 45:  'onUpdateBooksState' is assigned a value but never used  no-unused-vars

1 个答案:

答案 0 :(得分:2)

它是一个EsLint警告,可以防止您声明未使用的变量。

在此行中,您声明(不使用)变量

const { onUpdateShelf, books, onUpdateBooksState } = this.props

变量booksonUpdateBooksState不会在代码中的任何位置使用。

摆脱它们并将线路改为

const { onUpdateShelf } = this.props