从redux传递的调用方法从child反应到parent

时间:2017-06-02 09:32:08

标签: javascript reactjs redux

我坚持使用从我的主根组件传递到我的嵌套组件的调用方法。我从redux传递了这个函数,不知何故我遇到了问题,我无法执行它......

postActions.js

  //this method get called when screenshot captured
func detectScreenShot()  {
    let mainQueue = OperationQueue.main
    NotificationCenter.default.addObserver(forName: NSNotification.Name.UIApplicationUserDidTakeScreenshot,
                                           object: nil,
                                           queue: mainQueue,
                                           using: { notification in
                                            WEBSERVICE_INTERFACE.webServiceWithPostJSONParameters(param: nil, methodName: Constants.URLs.screenshot, headers: Constants.Headers.urlEncoded, showProgress: false, completion: { (response) in

                                                if let response = response{
                                                    let response = BaseResponse(JSONString : response)
                                                    if let message = response?.message{
                                                        LIMITUtils.showAlertMessage(message: message)
                                                    }
                                                }

                                            })

    })
}

App.js(主要根组件)

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

同样在我的App组件(root)中,我有这个PropsRoute的渲染方法,就像普通路线一样,但允许我传递道具......

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

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

Posts.js

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

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

Post.js(我应该执行它)

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

最后 const LabelDelete

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

所以这里的东西不会工作,我收到错误 TypeError:_this2.deletePost不是handleDelete的函数,我不知道在哪里绑定这个 ...

但它起作用,因为我没有使用这种方式与redux 它是

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

handleDelete 功能看起来像这样:

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

这很有效,但我不想这样使用它,我希望它更清楚。有帮助吗?感谢

1 个答案:

答案 0 :(得分:2)

在Posts.js中,您将deletePost作为Post组件的道具传递。因此,在Post.js中,this.deletePost应该更改为this.props.deletePost。

{{1}}