如何在ReactJS上使用嵌套的对象数据?

时间:2019-05-05 11:24:43

标签: reactjs axios jsx

  

我在评论中添加了答案

我使用Node.js创建了POST。我在邮递员中传递的数据看起来像这样。

  

{       “数量”:20,       “ with_tax”:{             “价格”:200,             “ currency”:“ lkr”         }

我这样创建了<div>(在Movie.jsx类中)

 render() {
    return (
      <div className="card" style={{ width: "25rem" }}>
        <form onSubmit={this.props.onPostData}>

含税价分部

    <div
                className="wrap-input100 validate-input bg1"
                data-validate="Please Type Running Time"
              >
                <span className="label-input100">With Tax Price</span>
                <input
                  type="number"
                  name="with_tax_price"
                  placeholder="With Tax Price"
                  className="form-control"
                  onChange={this.props.onDataChange}
                />
              </div>

含税种div

              <div
                className="wrap-input100 validate-input bg1"
                data-validate="Please Type Running Time"
              >
                <span className="label-input100">With Tax Currency</span>
                <input
                  type="text"
                  name="with_tax_currency"
                  placeholder="With Tax Currency"
                  className="form-control"
                  onChange={this.props.onDataChange}
                />
              </div>

在渲染方法中,我这样调用Movie类(在Movies.jsk类中)

class Movies extends Component {
  constructor() {
    super();

此状态

    this.state = {
      with_tax_price: "",
      with_tax_currency: "",
      quantity: ""
    };
  }

数据更改

  dataChange(ev) {
    this.setState({
      [ev.target.name]: ev.target.value
    });
  }

postData

  postData(ev) {
    ev.preventDefault();
    const with_tax_price = this.state.with_tax_price;
    const with_tax_currency = this.state.with_tax_currency;
    var with_tax;
    const quantity = this.state.quantity;

    this.setState({
      loading: true
    });

数据变量

    const data = {
      with_tax: { with_tax_price, with_tax_currency },
      quantity
    };

axios POST

    axios
      .post(apiEndpoint, data)
      .then(function(response) {
        console.log(response);
      })
      .catch(function(error) {
        console.log(error);
      });
  }

渲染方法

  render() {
    return (
      <Movie
        onPostData={this.postData.bind(this)}
        onDataChange={this.dataChange.bind(this)}
      />
    );
  }
}

1 个答案:

答案 0 :(得分:0)

将我的代码更改为此,

postData(ev)

{ 
ev.preventDefault();
         const with_tax = {
              price: this.state.with_tax_price,
              currency: this.state.with_tax_currency
            };
        }

数据变量

 const data = {
      with_tax,
      quantity
    };