没有onClick会触发功能

时间:2019-03-14 04:57:44

标签: javascript reactjs

我有一个来自api的列表,我使用fetch进行填充并答应。每个列表中都有一个删除按钮,因此当我单击删除时,该列表将被删除。 但是问题是,当我加载应用程序时,该函数会在没有onclick的情况下触发,而我却将该函数保留在onclick内。

该列表来自以下功能:

this.postdata_fire()

删除功能是这样的:

 deleteEachEntry(e,id,title){
      console.log("id:", id)
      console.log("title:", title)
      //      console.log('this.state.result_:: ',rating)
    }

用于重复列出和删除功能的html是:

 <tbody>
          {this.state.result_.map(re =>
         <tr>
         <td>{re.id} </td>
          <td> {re.title} </td>
         <td>{re.rating}</td>
          <td><button href="#">Edit</button><button href="#" onClick={this.deleteEachEntry(this,re.id,re.title)}>Delete</button></td>
          </tr> )}
          </tbody>

这是完整的代码:

import React, { Component } from 'react';
import logo from './logo.svg';
import {Table,Button, Modal, ModalHeader, ModalBody, ModalFooter} from 'reactstrap';
import './App.css';
import {Postdata} from './postdata';

class App extends React.Component {

  constructor(props){

    super(props);
      this.state = {
          hits: 'sduhyh',
          result_:[],
          modal:false,
          newBookData:{
            title:'',
            rating:''
          },
          pushadddata_to_result_:[]

      }
      this.toggle = this.toggle.bind(this);
      this.addBook = this.addBook.bind(this);
 //this.Postdata = this.Postdata.bind(this)
    }

    componentDidMount() {

      this.postdata_fire()
    }

    deleteEachEntry(e,id,title){
      console.log("id:", id)
      console.log("title:", title)
      //      console.log('this.state.result_:: ',rating)
    }

toggle(){
this.setState({modal: !this.state.modal})  
}



 addBook(url1 = '', data1 = this.state.newBookData) {
  // Default options are marked with *
    return fetch('http://localhost:3000/places', {
        method: "POST", // *GET, POST, PUT, DELETE, etc.
        mode: "cors", // no-cors, cors, *same-origin
        cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
        credentials: "same-origin", // include, *same-origin, omit
        headers: {
            "Content-Type": "application/json",
            // "Content-Type": "application/x-www-form-urlencoded",
        },
        redirect: "follow", // manual, *follow, error
        referrer: "no-referrer", // no-referrer, *client
        body: JSON.stringify(data1), // body data type must match "Content-Type" header
    })
    .then(response => response.json()).then(dat => {
      console.log(JSON.stringify(dat));
       //pushadddata_to_result_ = this.state.result_.push(dat)
       //this.state.pushadddata_to_result_.push(dat)
       console.log("this.state.pushadddata_to_result_:: ",dat);

       this.state.result_.push(dat);
       this.setState({modal: !this.state.modal}) 
      console.log('this.state.result_:: ',this.state.result_);

      // this.setState({result_:result_+pushadddata_to_result_})
      //this.setState({result_:pusheddata})
    }).catch(error => console.error(error)); // parses response to JSON
}





    postdata_fire() {
      Postdata('http://localhost:3000/places').then(result => {
      //  console.log("result:: %j",result);
        this.setState({result_: result});
      });
      console.log(this.state.result_)
     }

  render() {
    return (

      <div className="App container">

<Table>
          <thead>
            <tr>
            <th>#</th>
            <th>title</th>
            <th>Rating</th>
            <th>Actions</th>
            </tr>
            </thead>
            <tbody>
          {this.state.result_.map(re =>
         <tr>
         <td>{re.id} </td>
          <td> {re.title} </td>
         <td>{re.rating}</td>
          <td><button href="#">Edit</button><button href="#" onClick={this.deleteEachEntry(this,re.id,re.title)}>Delete</button></td>
          </tr> )}
          </tbody>
</Table>
<div>
        <Button color="danger" onClick={this.toggle}>{this.props.buttonLabel}</Button>
        <Modal isOpen={this.state.modal} toggle={this.toggle} className={this.props.className}>
          <ModalHeader toggle={this.toggle}>Modal title</ModalHeader>
          <ModalBody>
           <div>
              <label>title</label>
              <input type="text" onChange={(e)=>{
let {newBookData} = this.state;
newBookData.title = e.target.value
              }} />
            </div>

            <div>
              <label>Rating</label>
              <input type="text" onChange={(e)=>{
let {newBookData} = this.state;
newBookData.rating = e.target.value;

  }} />
            </div>

         </ModalBody>
          <ModalFooter>
            <Button color="primary"  onClick={this.addBook}>Do Something</Button>
            <Button color="secondary" onClick={this.toggle}>Cancel</Button>
          </ModalFooter>
        </Modal>
      </div>



        <button onClick={this.postdata_fire.bind(this)}></button>
      </div>
    );
  }
}

export default App;

请帮助。谢谢。

3 个答案:

答案 0 :(得分:0)

请从this.postdata_fire()中删除componentDidMount 并编写onClick in功能

<button onClick={()=>this.postdata_fire()}></button>

答案 1 :(得分:0)

class ClickExample extends React.Component {
    testFunction(p1){
        console.log(p1);
    }
    render() {
        return (
            <div>
              <div>
                {/*Following function will work immediately on render*/}
                <button onClick={this.testFunction("First Button onClick")}> 1 - Click Me </button>
              </div>
              <div>
                {/*You need to bind function in constructor for performance issues but this is another way to run functions onClick*/}
                <button onClick={this.testFunction.bind(this,"Second Button onClick")}> 2 - Click Me </button>        
              </div>
              <div>
                {/*I think this is the best way to using functions with parameters on click*/}
                <button onClick={ () => this.testFunction("Third Button onClick")}> 3 - Click Me </button>
              </div>
            </div>
        );
    }
}

您可以从以下位置查看我的示例 JSFiddle

答案 2 :(得分:0)

您的代码存在问题,就是每次render函数get都会执行您的deleteEachEntry函数调用。您不是binddeleteEachEntry变成onClick道具,而是调用该函数。要纠正错误的行为而无需进行过多校正,只需将onClick={this.deleteEachEntry(this,re.id,re.title)}行修改为onClick={this.deleteEachEntry.bind(this,re.id,re.title)}