首页 > 解决方案 > 在 React 中为我当前的资金添加一些钱

问题描述

我有一个带有一些 axios 响应的应用程序,例如 post、get 等,并且我有一个带有信用卡界面的组件,当我添加一些钱输入然后单击“添加钱”按钮时,我应该更新我当前的用这笔新钱存入账户,而不是替换,只需将这笔钱添加到我数据库中的当前资金中,我有这个代码,我是 React 的新手,所以任何帮助都会很好。

export default class PaymentForm extends React.Component {
    constructor(props) {
        super(props);
    
        this.handleInputFocus = this.handleInputFocus.bind(this);
        this.handleInputChange = this.handleInputChange.bind(this);
        this.onChangeMoney = this.onChangeMoney.bind(this);
        this.onSubmit = this.onSubmit.bind(this);
    
        this.state = {
            cvc: '',
            expiry: '',
            focus: '',
            name: '',
            number: '',
            money: '',
        };
      }
    


  handleInputFocus = (e) => {
    this.setState({ focus: e.target.name });
  }
  onChangeMoney(e) {
    this.setState({ money: e.target.value });
  }
  handleInputChange = (e) => {
    const { name, value } = e.target;
    
    this.setState({ [name]: value });
  }
  onSubmit(e) {
    e.preventDefault();


    const userObject = {
      money: this.state.money,
    };
    let url = window.location.href;
    url = url.replace("http://localhost:3000/wallet/", "");
    let _id = url;
    axios
      .put(`http://localhost:5000/profile/wallet/${_id}`, userObject)
      .then((res) => {
        console.log(res.data);
      })
      .catch((error) => {
        console.log(error);
      });

    this.setState({ money: "", });
  }
  
  
  render() {
.....

标签: reactjscrud

解决方案


如果您需要在当前资金中添加资金,则需要执行以下操作:

  • 从数据库中获取资金(this.state.money)
  • 用新钱设置一个变量并将其绑定到输入(this.state.currentMoney)
  • 当您执行 axios.put 时,您发送请求的正文、当前资金和输入中写入的资金的总和 (this.state.money + this.state.currentMoney)
this.state = {
            cvc: '',
            expiry: '',
            focus: '',
            name: '',
            number: '',
            money: '',
            currentMoney: '',
};

onChangeMoney(e) {
    this.setState({ inputMoney: e.target.value });
}

const userObject = {
      money: this.state.money + this.state.inputMoney,
    };

推荐阅读