2016-06-28 61 views
0

我遇到一个问题,其中this在我的商店中为我的React组件返回null。我相信我需要对此加以约束,但我不确定。我也在使用React Router,并将我的组件设置在一个包装中,这样我就可以将道具传递给它。任何帮助表示赞赏!React Store对`this`的值返回null

COMPONENT

import React from 'react'; 
import PaymentStore from './../store/paymentStore'; 

class InitialPaymentScreen extends React.Component { 
    constructor(props) { 
    super(props) 
    } 
    render() { 
    console.log(this.props) 
    return (
     <div className="payment-form-submit" onClick={this.props.store.init}>Next</div> 
    ); 
    } 
} 

class PaymentForm extends React.Component { 
    constructor(props) { 
    super(props) 
    } 

    render() { 
    return (
     <section className="main-content payment-form-wrapper"> 
     <InitialPaymentScreen store={this.props.store}/> 
     </section> 
    ); 
    } 
} 

export default class PaymentFormWrapper extends React.Component { 
    render() { 
    return (
     <PaymentForm store={PaymentStore} mode="foo"/> 
    ); 
    } 
} 

STORE

let PaymentStore = { 
    handleClickNext() { 

    console.log("hello") 

    }, 
    init() { 
    console.log(this) // returns null 
    this.handleClickNext(); // cannot read property of null 
    }, 
}; 

export default PaymentStore; 

回答

0

看起来像你需要确实绑定。你可以通过改变

<div className="payment-form-submit" onClick={this.props.store.init.bind(this.props.store)}>Next</div> 

# or 

var init = this.props.store.init.bind(this.props.store); 
<div className="payment-form-submit" onClick={init}>Next</div> 

或者,如果InitialPaymentScreen只需要initstore,结合可在PaymentForm发生,InitialPaymentScreen只能接收功能。

绑定需要完成,因为在某些方面,javascript是独一无二的。

通常情况下,函数的this必然会被从字面上绑定到它被调用的地方。在你的情况下,store.init()意味着init函数具有this作为商店。

现在,如果您将store.init分配给一个变量并调用它,它不知道什么是this! (this可能是人们学习JS的最常见的问题) - 因为调用时,它试图通过了解哪些对象是功能推断this存储在

要获得使函数知道什么是它的上下文那么,你有两个选项基本上都是:

a。 fn.bind(something),它返回一个绑定函数,或者

b。创建一个匿名函数,调用该函数

+0

太棒了,就像一个魅力。你能否澄清为什么我必须把这个绑定? – u111937

+0

当然,我刚刚更新了一些背景的答案! –