2017-06-02 81 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