简体   繁体   English

没有onClick会触发功能

[英]function fires without onClick

I have a list coming from api that i am populating using fetch and promise. 我有一个来自api的列表,我使用fetch和promise进行填充。 There is a delete button in each list, so that when i click delete, that list is deleted. 每个列表中都有一个删除按钮,因此当我单击删除时,该列表将被删除。 But the problem is that when i load the app, the function fires without onclick, whereas i kept the function inside onclick. 但是问题是,当我加载应用程序时,该函数会在没有onclick的情况下触发,而我却将该函数保留在onclick内。

the list is coming from the following function: 该列表来自以下功能:

this.postdata_fire()

the delete function is this: 删除功能是这样的:

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

the html for repeating list and delete function is : 重复列表和删除功能的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>

This is the full code: 这是完整的代码:

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;

please help. 请帮忙。 Thanks. 谢谢。

请从componentDidMount删除this.postdata_fire()并在函数中写入onClick

<button onClick={()=>this.postdata_fire()}></button>
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>
        );
    }
}

You can check my example from JSFiddle 您可以从JSFiddle检查我的示例

您的代码的问题是每次渲染函数get都会执行deleteEachEntry函数调用。您并未bind deleteEachEntry bindonClick deleteEachEntry ,而是您正在调用该函数。要纠正错误的行为而无需太多校正,只需修改onClick={this.deleteEachEntry(this,re.id,re.title)}onClick={this.deleteEachEntry.bind(this,re.id,re.title)}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM