【问题标题】:Passing state into an Ajax call ReactJS and Rails将状态传递给 Ajax 调用 ReactJS 和 Rails
【发布时间】:2016-04-11 09:34:07
【问题描述】:

我有一个 ProductItem 组件,当用户单击“添加到购物篮”时,它会执行 AJAX 发布调用以创建购物篮项目。

但是,我目前似乎无法将状态传递给 Ajax 调用,因此它缺少所需的动态数据。

当我在 chrome 上签入 react 开发人员工具时,组件看起来像这样,并且状态在 Product Item 组件上设置正确。

class ProductItem extends React.Component{

constructor() {
    super()

    this.state = { 
        name: '',
        price: 0,
        code: '',
        id: ''
    }
}

componentWillMount() {
    this.setState( {
        name: this.props.data.name,
        price: this.props.data.price,
        code: this.props.data.code,
        id: this.props.data.id
    })
}

addtoBasket(props) {
    console.log(props.name) /* RETURNS UNDEFINED */
    $.ajax({
        type: "POST",
        url: "/items",
        dataType: "json",
        data: {
            item: {
                name: 'Trousers',
                price: 52.00,
                code: 'T01'
            }
        },
        success: function() {

            console.log("success");
        },
        error: function () {
            console.log("error");
        }
    })
}

render(){
    let productName = this.props.data.name
    let productPrice = this.props.data.price
    let productCode = this.props.data.code
    let productImg = this.props.data.image_url

    return (
        <div className="col-xs-12 col-sm-4 product">
            <img src={productImg}/>
            <h3 className="text-center">{productName}</h3>
            <h5 className="text-center">£{productPrice}</h5>
            <div className="text-center">
                <button onClick={this.addtoBasket.bind(this.props)} className="btn btn-primary">Add to Basket</button>
            </div>
        </div>
    )
}

}

我该如何解决这个问题并正确地将状态或道具传递给调用?

【问题讨论】:

    标签: javascript jquery ruby-on-rails ajax reactjs


    【解决方案1】:

    将您的按钮更改为以下代码

    <button onClick={this.addtoBasket.bind(this)} className="btn btn-primary">Add to Basket</button>
    

    然后你就可以得到这个的上下文了。

    或者其他方式

     <button onClick={this.addtoBasket.bind(this , this.props)} className="btn btn-primary">Add to Basket</button>
    

    并且在addtoBasket方法中

    addtoBasket(props){
      console.log("Prrops" , props)
    }
    

    应该可以的:)

    【讨论】:

      【解决方案2】:

      问题在于 this.addtoBasket.bind(this.props) 调用 - bind 方法的参数将在绑定函数中变为 this。像这样调用它会将props 绑定为this,而不是类。

      您可能想改用this.addtoBasket.bind(this)

      addtoBasket 函数的参数将是 onClick 事件,而不是道具。

      【讨论】:

        猜你喜欢
        • 2021-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-17
        • 1970-01-01
        • 1970-01-01
        • 2017-06-03
        相关资源
        最近更新 更多