##Reactで画面初期表示時にファンクションが実行される
ReactでonClickイベントハンドラで指定している削除機能ファンクションが、画面初期表示時に実行されてしまいます。
初期表示時に実行されないようにするにはどのようにしたら良いのでしょうか。
####ソース
App.js
import React, {Component} from 'react'; import './App.css'; import Item from './components/ItemList/Item.js'; import axios from 'axios'; import Header from "./components/Header/Header"; const endPoint = process.env.REACT_APP_ENDPOINT + "/items"; class App extends Component { constructor(props) { super(props); this.state = { data: [],//アイテムの複数データ格納変数 keyword: '', id: '', }; //thisがこのクラス自体のことだということを教えておく //全件取得メソッド this.getAllItems = this.getAllItems.bind(this); //アイテム検索メソッド this.itemsSearch = this.itemsSearch.bind(this); this.itemDelete = this.itemDelete.bind(this); } //初期表示全件取得 componentDidMount = () => { this.getAllItems(); } //全件取得メソッド getAllItems = () => { axios({ method: 'GET', url: endPoint, headers: { 'Content-type': 'application/json', } }).then((results) => { if (!('errors' in results)) { this.setState({data: results.data}); } else { //取得できなかった時の処理 } }); }; //アイテム検索メソッド itemsSearch = (keyword) => { axios({ method: 'GET', url: endPoint, params: {name: keyword}, headers: { 'Content-type': 'application/json', } }).then((results) => { //正常に取得できた場合とエラーとなった場合の分岐 if (!('errors' in results)) { this.setState({data: results.data}); } else { //取得できなかった時の処理 } }); }; //アイテム削除メソッド itemDelete = (id) => { axios({ method: 'DELETE', url: endPoint+'/'+id, headers: { 'Content-type': 'application/json', } }).then(() => { this.getAllItems(); }); }; render() { const items = this.state.data.map((item) => { return ( <Item key={item.id} item={item} itemDelete={()=>this.itemDelete(item.id)} /> ); }); return ( <div className="App"> <Header itemsSearch={keyword => this.itemsSearch(keyword)} getAllItems={() => this.getAllItems()} /> <div>{items}</div> </div> ); } } export default App;
ItemDeleteButton.js
import React from 'react'; const ItemDeleteButton = (props) =>{ return ( <button onClick={props.itemDelete(props.id)}> Delete </button> ); } export default ItemDeleteButton;
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/03/30 07:15