簡體   English   中英

從redux傳遞的調用方法在從子級到父級的反應中

[英]Call method passed from redux in react from child to parent

我陷入了從我的主根組件傳遞到非常嵌套的組件的調用方法的困境。 我正在從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));
        }
    }
}

同樣在我的App組件(root)中,我具有與此PropsRoute的render方法,這類似於普通路線,但允許我傳遞道具...

<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的函數,我不知道在哪里綁定 ...

但是它起作用了,因為我沒有在redux中使用這種方式

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

這行得通,但我不想這樣使用它,我希望它更清晰。 有什么幫助嗎? 謝謝

在Posts.js中,您將deletePost作為Post組件的支持傳遞。 因此,在Post.js中,this.deletePost應該更改為this.props.deletePost。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM