2017-06-02 12 views
0

私は主なルートコンポーネントから非常にネストされたコンポーネントに渡された呼び出しメソッドを使用しています。私はReduxのから、その関数を渡していますし、何とか私は問題を抱えていると私はそれを実行することはできません...子から親への反応でreduxから渡された呼び出しメソッド

postActions.js

export function deletePost(id) { 
     const request = axios.delete(`http://localhost:3000/api/posts/${id}`); 
     return { 
     type: "DELETE_POST", 
     payload: request 
    } 
} 

App.js(メインルートコンポーネント)私は通常のルートのようですが、私は小道具を渡すことができ、このPropsRouteでrenderメソッドを持っている私のアプリケーションコンポーネント(ルート)でまた

import {deletePost} from "../actions/postActions"; 
const mapStateToProps = (state) => { 
    return { 
     post: state.postReducer 
    }; 
}; 

const mapDispatchToProps = (dispatch) => { 
    return { 
     deletePost:(id)=>{ 
      dispatch(deletePost(id)); 
     } 
    } 
} 

...

<PropsRoute path={"/posts/:id/:title"} deletePost={this.props.deletePost} component={Posts} {...this.props.match} /> 

export default connect(mapStateToProps, mapDispatchToProps)(App); 

Posts.js

render(){  
    return(
     <div> 
      <main> 
       <Post deletePost={this.props.deletePost)} /> 
      </main> 
     </div> 
    ); 
    } 

Post.js(ここで私はそれを実行する必要があります)

render(){ 
    return (
    <LabelDelete handleDelete={this.deletePost} id={id} {...this.props.children}/> 
    ) 
} 

そして最後にのconst LabelDelete

const LabelDelete = (props) => (<span><button onClick={props.handleDelete}>Delete</button></span>); 

だからここに何かが仕事を文句を言わない、と私はエラーTypeError例外を取得しています:_this2.deletePostはhandleDeleteでは関数ではないと私はどここのをバインドするには知らない...

が、私は」didnのため、それが働きました

handleDelete(){ 
    var id = this.props.id; 
    $.ajax({ 
     type:"DELETE", 
     url:`http://localhost:3000/api/posts/${id}`, 
     success: function(res) { 
      setTimeout(function() { 
       location.pathname="/user"; 
      }, 500); 
     }.bind(this), 
     error: function(xhr, status, err) { 
      console.error(xhr, status, err.toString()); 
     }.bind(this) 
     }); 
    } 
:トンReduxの でこの方法を使うことが

<LabelDelete handleDelete={this.handleDelete.bind(this)} id={id} {...this.props.children}/> 

そしてhandleDelete関数はこのように見えました

これはうまくいきましたが、私はこれをこのように使いたくないので、もっと明確にしたいと思います。どんな助け?ありがとう

答えて

2

あなたのPosts.jsでは、postPostをPostコンポーネントの小道具として渡しています。したがって、Post.jsではthis.deletePostをthis.props.deletePostに変更する必要があります。

render(){ 
    return (
     <LabelDelete handleDelete={this.props.deletePost} id={id} 
      {...this.props.children}/> 
    ) 
} 
+0

はい、しかしdeletePostは関数なので、IDを渡す必要があります。どのように書きますか? **()=> this.props.deletePost(id)**のように?もし私がそれを書いても私はエラーを受け取ります_this2.props.deletePostは関数ではありません – Ivan

+0

@Ivanその場合、ちょうどDeleteIdをLabelDeleteの別の小道具として渡し、this.props.handleDeleleteのようなLabelDeleteコンポーネントで使用することができます.props.deleteId) – SLee

関連する問題