简体   繁体   中英

Call method passed from redux in react from child to parent

i'm stucked with calling method passed from my main root component to my very nested component. I am passing that function from redux, and somehow I am having problem and i can't execute it...

postActions.js

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

App.js(main root component)

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

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

Also in my App component(root) i have render method with this PropsRoute which is like normal route but allows me to pass props...

<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(here i should to execute it)

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

And finally const LabelDelete

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

So something here wont work, and i am getting error TypeError: _this2.deletePost is not a function at handleDelete and i dont know where to bind this ...

But it worked since i didn't use this way with redux it was

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

And handleDelete function looked like this:

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

This worked, but i don't want to use it like this, i want it to be more clear. Any help? Thanks

In your Posts.js, you are passing deletePost as props of Post component. Thus, in Post.js, this.deletePost should be changed to this.props.deletePost.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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