【问题标题】:how post props redux React如何 post props redux React
【发布时间】:2020-06-04 22:42:56
【问题描述】:

我想解释一下我今天遇到的问题。

我无法发布“this.props.total”, 我不明白如何发布道具,你能帮我吗? 目前道具工作正常。

import React, { Component } from 'react';
import { CardText, } from 'reactstrap';
import { connect } from 'react-redux'

class thisPropsFortotal extends Component {

handleSubmit = (e) => {
    e.preventDefault();
    const config = {
     method: "POST",
     headers: {
       "Content-Type": "application/json",
     },
     body: JSON.stringify({this.props.total}),
    };

     const url = entrypoint + "/alluserpls";
     fetch(url, config)
     .then(res => res.json())
     .then(res => {
       if (res.error) {
         alert(res.error);
       } else {
         alert(`ajouté avec l'ID ${res}!`);
       }
     }).catch(e => {
       console.error(e);

       }).finally(() => this.setState({ redirect: true }));
    }
   render() {
    return (
        <div>
            <form onSubmit={this.handleSubmit}>
  <button type="submit">Add</button>
  </form>
            <CardText>{this.props.total} € </CardText>
        </div>
    );
   }
 }
 const mapStateToProps = (state) => {
  return {
    total: state.addedItems.reduce((acc, item) => { return acc + (item.quantity * 
  item.price) }, 0)
    //addedItems: state.addedItems
  }
  }

export default connect(mapStateToProps)(thisPropsFortotal)

您知道如何解决这个问题吗?内夫

【问题讨论】:

  • 你能在设置状态之前console.log(this.props.total)吗?

标签: javascript reactjs axios fetch


【解决方案1】:

您正在尝试对{this.props.total} 进行字符串化,这是无效的语法。

您可以传递一个明确定义total 键的对象,如下所示:

body: JSON.stringify({total: this.props.total}),

或者,简单地将this.props 对象本身字符串化:

body: JSON.stringify(this.props),

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-01
    • 2018-09-29
    • 2016-07-03
    • 2017-10-20
    • 2019-07-06
    • 2021-03-20
    相关资源
    最近更新 更多