簡體   English   中英

React 中的 no-unused-expressions

[英]no-unused-expressions in React

我正在 React 中編寫包含搜索欄的代碼。 用戶輸入一個關鍵字,我的代碼顯示包含該關鍵字的所有結果。 但是,我的代碼不起作用,並且出現 no-unused-expressions 錯誤。

我有一系列書籍,每當我的用戶輸入關鍵字時,就會顯示標題中包含該關鍵字的書籍列表。 此外,我希望我的輸入欄首先有一個值,當頁面加載時,它會查找具有關鍵字的書籍。

這是我的代碼:

import React from 'react';
import BooksContainer from './BooksContainer';


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

        this.state ={
            books: [
                {
{"title": "aaa" ,"description" : "abcdef" , "categories" : ["xyz"]},
{"title": "abc" , "description" : "abcdef" , "categories" : ["xyzr"]},
{"title": "abcd" , "description" : "abcdef" , "categories" : ["xyzrp"]}
                  }
            ],
            searchTerm :'harry potter',
            filterDisplay : []
             };


    }

    handleChange =(e) => 
    {
        this.setState ({searchTerm: e.target.value });
        let oldList = books.map(book => {
            return {
                book: book.title.toLowerCase(), book: book.categories.toLowerCase(), book: book.description.toLowerCase()
            };
        });

        if(searchTerm !== "")
        {
            let newList = oldList.filter(book => book.title.includes(this.state.searchTerm.toLowerCase()));
            this.setState ({filterDisplay: newList });
        }
    }


    render(){ 

        return(

            <div>

                <form onSubmit = {this.handleSearch}>
                    <h6>Search for the books</h6>
                    <input type = "text"  value = {this.state.searchTerm} onChange = {this.handleChange} />
                    <button type = "submit">Search</button>
                </form>

                    <BooksContainer books ={this.state.searchTerm.length < 1 ? this.state.books:this.state.filterDisplay} />

            </div>
        );
    }
}

export default BookList;



據我所知,“no-unused-expressions”並不是您的代碼無法正常工作的原因。 它來自 eslint 或其他 linter,它只是意味着聲明您沒有在代碼中使用的東西,而不是破壞代碼問題: https : //eslint.org/docs/rules/no-unused-expressions

當然,您可以將此行添加到您的 .eslintrc 規則中:

rules: {
'no-unused-expression': 0,
}

從我看到的情況來看,您應該擺脫書籍數組周圍的 {} - 第 11 和 15 行。在第 29 行,您嘗試返回相同的鍵名 3 次:

book: book.title.toLowerCase(), book: book.categories.toLowerCase(), book: book.description.toLowerCase()

這第一本“書”只是一把鑰匙,您不應該使用 3 個相同的鑰匙。 例如,這種方式很好:

book: [book.title.toLowerCase(), book.categories.toLowerCase(), book.description.toLowerCase()]

let oldList 應該替換為const oldList。

let newList 也是一樣,應該用const替換。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM