2017-06-02 60 views
0

我用调用方法从我的主根组件传递给我非常嵌套的组件。我传递给函数的终极版,不知何故我有问题,我不能执行它...调用方法从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(主根成分)

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

const mapDispatchToProps = (dispatch) => { 
    return { 
     deletePost:(id)=>{ 
      dispatch(deletePost(id)); 
     } 
    } 
} 
在我的应用程序组件(根),我有渲染方法与此PropsRoute这就好比是正常的路线,但可以让我通过道具

也...

<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}/> 
    ) 
} 

最后常量LabelDelete

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

所以这里的东西不会工作,而我得到的错误类型错误:_this2.deletePost是不是handleDelete一个功能,我不知道在哪里绑定这个 ...

但它的工作,因为我没有” T选用这种方式与终极版 是

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

而且handleDelete功能是这样的:

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) 
     }); 
    } 

这工作,但我不想这样使用它,我希望它更清楚。任何帮助?谢谢

回答

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的另一个道具,并像这样在LabelDelete组件中使用this.props.handleDelelete(this .props.deleteId) – SLee

相关问题