【问题标题】:Function not working on onClick event in React.js函数在 React.js 中的 onClick 事件上不起作用
【发布时间】:2019-03-07 08:23:32
【问题描述】:

我正在编写一个反应程序,其中数据将通过 API 获取并显示在表格中。有 3 个主要文件 App.js、Table.js 和 Search.js 和 Button.js。 正在显示数据,搜索正在工作,但删除按钮不起作用。 我已经为删除按钮编写了一个函数,我猜其中有问题,但不知道是什么。

App.js

import React, { Component } from 'react';
import './App.css';
import Table from './components/Table';
import Search from './components/Search';


//API config
const DEFAULT_QUERY = 'react';
const PATH_BASE = 'https://hn.algolia.com/api/v1';
const PATH_SEARCH = '/search';
const PARAM_SEARCH = 'query=';

const url = `${PATH_BASE}${PATH_SEARCH}?${PARAM_SEARCH}${DEFAULT_QUERY}`;


class App extends Component {
  constructor(){
    super();
    //here searchText is set to DEFAULT_QUERY which will return the result for keyword "redux"
    //refer line 8 to change
    this.state={
      searchText:'',
      result:''
    }
    this.onDismiss=this.onDismiss.bind(this);
    this.onSearchChange=this.onSearchChange.bind(this);
    this.searchStories=this.searchStories.bind(this);

    //this.isSearched=this.isSearched.bind(this);
  }

  //to add a delete button
  onDismiss=(id)=>{
    //filter out item array and return results with no matched id
    const deleteList=this.state.list.filter(item=>item.objectID!==id);
    //setting state of list to lastest deleteList
    this.setState({
      result:deleteList
    })  
  }
  //to add a search bar
  onSearchChange=(e)=>{
    //set state to value in search bar
    this.setState({
      [e.target.name]:e.target.value
    })
  }

  searchStories=(result)=>{
    this.setState({
      result
    });
  }
  //after mounting will fetch the api data
  componentDidMount(){
    fetch(url)
    .then(response => response.json())
    .then(result => this.searchStories(result));
  }

  render() {
    const {result,searchText}=this.state;
    if(!result){
      return null;
    }
    return(
      <div className="page">
          <div className="interactions">

        <Search
       searchText={searchText}
       onSearchChange={this.onSearchChange}
       >
        Search
        </Search>
        </div>
       <Table
       list={result.hits}
       onDismiss={this.onDismiss}
       searchText={searchText}/>

      </div>

    )

  }
}

export default App;

Table.js

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

const Table=(props)=>{
    const {list,searchText,onDismiss}=props;
    return(
        <div className="table">

       {/*Filter out item title and search title and give away results from item array */}
        {list.filter((item)=>{
          {/*The includes() method determines whether an array includes a certain value among its entries
          , returning true or false as appropriate. */}
          return item.title.toLowerCase().includes(searchText.toLowerCase());}).map((item)=>{

            return(

            <div key={item.objectID} className="table-row">
                  <span style={{ width: '40%' }}>
                        <a href={item.url}>{item.title}</a>
                        </span>
                        <span style={{ width: '30%' }}>
                        {item.author}
                        </span>
                        <span style={{ width: '10%' }}>
                        {item.num_comments} comments
                        </span>
                        <span style={{ width: '10%' }}>
                        ${item.points} points
                        </span>
                        <span style={{ width: '10%' }}>
                  <Button className="button-inline" onClick={()=>onDismiss(item.objectID)}>delete</Button>
                  </span>

            </div>

          )})}
      </div>
    )

  }


export default Table;

Button.js

import React from 'react';

const Button=(props)=>{

    const{onclick,className='',children}=props;
    return(
      <div>
          <button onClick={onclick} className={className} >{children}</button>
      </div>
    )

  }


export default Button;

【问题讨论】:

  • 尝试将 onDismiss={this.onDismiss} 更改为 onDismiss={() => this.onDismiss}

标签: javascript reactjs ecmascript-6 react-redux


【解决方案1】:

您的按钮需要稍作修改:

<button onClick={onClick} className={className} >{children}</button>

处理程序需要引用传入的 props,其中是 this.props.onClick,而不是 this.props.onclick(你有)。

你遇到的错误可以通过修改App.js来修复:

onDismiss = id => {
  if (id) {
    const deleteList = this.state.list.filter(item => item.objectID !== id);
    // setting state of list to lastest deleteList
    this.setState({
      result:deleteList
    }) 
  }
}

【讨论】:

    【解决方案2】:

    在Button组件变化

    const{onclick,className='',children}=props;
    

    const{onClick,className='',children}=props;
    

    此外,您似乎还没有在状态中设置列表,因此当您尝试访问 this.state.list.filter 时,它会抛出错误。

    onDismiss=(id)=>{    
      const deleteList=this.state.result.hits.filter(item=>item.objectID!==id);    
      this.setState({
      result:{...this.state.result,hits:deleteList}
    })  
    

    }

    【讨论】:

    • 它是onClick 而不是onclick,你打错了
    • @Treycos 不起作用。它使应用程序崩溃并给出错误:TypeError: Cannot read property 'filter' of undefined
    • @user11066242 在代码中` const deleteList=this.state.list.filter(item=>item.objectID!==id); ` 您尝试访问 this.state.list 的 onDismiss 函数。列表来自哪里?您是否将列表设置为某处的状态
    • @Muljayan 明白了,当机立断。这是一个旧代码,我没有根据状态值更新它。相反,我将它替换为 result.hits.filter 并且它起作用了。谢谢
    • @user11066242 就像你的编辑由于某种原因被我的编辑覆盖了。尝试再次编辑。
    猜你喜欢
    • 2019-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-30
    • 1970-01-01
    相关资源
    最近更新 更多