Javascript 在React中获取POST-API的响应

Javascript 在React中获取POST-API的响应,javascript,reactjs,api,post,response,Javascript,Reactjs,Api,Post,Response,我有一个POST API,在执行时需要在div中呈现响应结果 我正在使用React.js和Redux 这是存储api的服务 const addMP3Request = async (payload) => { const formData = new FormData(); formData.append("titre",payload.payload.titre); formData.append("description",payload.payload.

我有一个POST API,在执行时需要在div中呈现响应结果 我正在使用React.js和Redux

这是存储api的服务

const addMP3Request = async (payload) => {


    const formData = new FormData();

    formData.append("titre",payload.payload.titre);
    formData.append("description",payload.payload.description);
    formData.append("type",payload.payload.type);
    formData.append("file1",payload.payload.fichier1);

    const wsResponse = await axios.request({
        method: 'post',
        url: `http://localhost:3000/api/watson_tones/analyzeMP3`,
        data: formData,
        config: {
            headers: {
                'Content-Type': `multipart/form-data`,
                'Accept': 'application/json',
            }
        }

    });
    return wsResponse;
}
这是我的减速机

  const INIT_STATE = {
    responseData: ''
  };

  export default (state = INIT_STATE, action) => {
    switch (action.type) {


      case ADD_MP3: {
        return {
          ...state,
          responseData: action.responseData
        }

      }

      default:
        return state;
    }
  }
这就是行动:

export const addMP3Action = (titre,description,type,fichier1) => {

    return {
    type: ADD_MP3,
    payload: {
      titre: titre,
      description: description,
      type: type,
      fichier1:fichier1
    },

    };

};
这是我添加MP3的视图,我想存储这个api的响应

import React, { Component } from "react";
import { Button, Form, Input, Select} from "antd";
import { connect } from "react-redux";
import {addMP3Action} from "../../appRedux/actions/Mp3";
import SweetAlert from "react-bootstrap-sweetalert";
import AudioPlayer from "react-h5-audio-player";

const FormItem = Form.Item;
const Option = Select.Option;

class AjoutExtrait extends Component {

  constructor() {
    super();
    this.state = {
      selectedFileUrl: '',
      selectedFileName:"",
      showPlayer:false,
      alertMessage: "",
      alertSuccess: false,
      alertWarning: false,
      titre:'',
      description:'',
      type:"",
      responseData:''

    };
    this.onFileChange = this.onFileChange.bind(this)
    this.handleChangeTitre = this.handleChangeTitre.bind(this)
    this.handleChangeDescription = this.handleChangeDescription.bind(this)
    this.handleChangeType = this.handleChangeType.bind(this)
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.responseData !== prevState.responseData && nextProps.responseData) {
      //console.log('responseDataaa',nextProps.responseData)
      return { responseData: nextProps.responseData };

    } else
    //console.log('responseDataaa',nextProps.responseData)
     return null;
  }

  onFileChange(e) {
    this.setState({ file: e.target.files[0] });
    this.setState({ selectedFileUrl: URL.createObjectURL(e.target.files[0]) });
    this.setState({ showPlayer: true });
    this.setState({ selectedFileName: e.target.files[0].name });
  }

  handleChangeTitre(event) {
    this.setState({titre: event.target.value});
  }

  handleChangeDescription(event) {
    this.setState({description: event.target.value});
  }
  // handleChangeType(event) {
  //   this.setState({type: event.target.value});
  // }
  handleChangeType = (value) => {
   let  selectedFilter = value;
    this.setState({type: selectedFilter});
  }

  handleFormSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.props.addMP3Action(this.state.titre,this.state.description,this.state.type,this.state.file);
       }
    });
  }

  onConfirmAlertMessage = () => {
    this.setState({
      alertMessage: "",
      alertSuccess: false,
      alertWarning: false,
    });
  };

  renderAlertMessage(){
    var intl = this.props.intl;
    const { alertSuccess, alertWarning, alertMessage } = this.state;

    return(
     <div>
        <SweetAlert
          show={alertSuccess}
          success
          title={alertMessage !== "" ?(intl.formatMessage({id: alertMessage})):""}
          onConfirm={this.onConfirmAlertMessage}>
        </SweetAlert>

        <SweetAlert show={alertWarning}
          warning
          title={alertMessage !== "" ?(intl.formatMessage({id: alertMessage})):""}
          onConfirm={this.onConfirmAlertMessage}>
        </SweetAlert>
     </div>
    );
  }

  render() {
    // const { getFieldDecorator } = this.props.form;
   console.log("gfgfg",this.props.responseData)
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 24 },
        md: { span: 12 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 },
        md: { span: 12 },
      },
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 },
        md: { span: 20 },
      },
    };

    return (
      <div ref={this.props.scrollDivAjoutExtrait} className="cm-comedien-mp3-card-ajout">
        <h2>Ajouter un Extrait MP3</h2>
        <p> gfdffd {this.props.responseData}</p>
        <Form onSubmit={this.handleFormSubmit}>

          <FormItem {...formItemLayout}>
            <p>Titre</p>
              <Input value={this.state.titre} onChange={this.handleChangeTitre}/>
          </FormItem>

          <FormItem {...formItemLayout}>
            <p>Description</p>
              <Input value={this.state.description} onChange={this.handleChangeDescription}/>
          </FormItem>

          <FormItem {...formItemLayout}>
          <p>Type</p>
              <Select
              // name="type"
              // value={this.state.type} 
              defaultValue=""
              onChange={this.handleChangeType}
             >

                <Option value="1">type 1</Option>
                <Option value="2">type 2</Option>
              </Select>   
          </FormItem>
          <FormItem {...formItemLayout}>
              <p>Upload fichier MP3</p>
              <div className="cm-comedien-mp3-ajout-file-container">
                <input  style={{ opacity: "0",display:"none" }} 
                        type="file" 
                        id="file" 
                        name="file" 
                        title="Choisir un fichier mp3" 
                        accept=".mp3" 
                        onChange={this.onFileChange} 
                />
                <div class="cm-comedien-mp3-ajout-file-name">
                  <span style={{ paddingRight: "12px" }}>
                    {this.state.selectedFileName}
                  </span>
                </div>
                <div class="cm-comedien-mp3-ajout-file-button">
                  <label for="file">
                    upload
                  </label>
                </div>
              </div>
          </FormItem>

          {this.state.showPlayer ?
          <FormItem {...formItemLayout}>

            <AudioPlayer
              type="audio/mp3"
              position="inline"
              nomComedien=""
              titre={this.state.selectedFileName}
              fileName={this.state.selectedFileName}
              url={this.state.selectedFileUrl}
            />  

          </FormItem>
          :null}

          <FormItem {...tailFormItemLayout}>
            <Button type="primary" htmlType="submit">
              Ajouter
            </Button>
          </FormItem>
        </Form>

        <div style={{width:"100%",height:"400px",background:"white",marginBottom:"50px"}}>

        </div>

        {this.renderAlertMessage()}

      </div>
    );
  }

}

const AjoutExtraitForm = Form.create()(AjoutExtrait);

const mapStateToProps = ({ mp3 }) => {
  const {
    responseData
  } = mp3;

  return {
    responseData
  }
};


export default connect(mapStateToProps, { addMP3Action })(AjoutExtraitForm);
import React,{Component}来自“React”;
从“antd”导入{按钮、表单、输入、选择};
从“react redux”导入{connect};
从“../../appRedux/actions/Mp3”导入{addMP3Action};
从“react bootstrap SweetAlert”导入SweetAlert;
从“react-h5-audio-player”导入AudioPlayer;
const FormItem=表单项;
const Option=Select.Option;
类AjoutExtrait扩展组件{
构造函数(){
超级();
此.state={
selectedFileUrl:“”,
selectedFileName:“”,
表演者:错,
警报消息:“”,
成功:错,
警告:错误,
标题:'',
说明:“”,
类型:“,
响应数据:“”
};
this.onFileChange=this.onFileChange.bind(this)
this.handleChangeTitre=this.handleChangeTitre.bind(this)
this.handlechangescription=this.handlechangescription.bind(this)
this.handleChangeType=this.handleChangeType.bind(this)
}
静态getDerivedStateFromProps(下一步,上一步){
if(nextrops.responseData!==prevState.responseData&&nextrops.responseData){
//console.log('responseDataaa',nextrops.responseData)
返回{responseData:nextrops.responseData};
}否则
//console.log('responseDataaa',nextrops.responseData)
返回null;
}
onFileChange(e){
this.setState({file:e.target.files[0]});
this.setState({selectedFileUrl:URL.createObjectURL(e.target.files[0]));
this.setState({showPlayer:true});
this.setState({selectedFileName:e.target.files[0].name});
}
handleChangeTitre(事件){
this.setState({titre:event.target.value});
}
handleChangeDescription(事件){
this.setState({description:event.target.value});
}
//handleChangeType(事件){
//this.setState({type:event.target.value});
// }
handleChangeType=(值)=>{
让selectedFilter=值;
this.setState({type:selectedFilter});
}
handleFormSubmit=(e)=>{
e、 预防默认值();
this.props.form.validateFieldsAndScroll((错误,值)=>{
如果(!err){
this.props.addmp3操作(this.state.titre,this.state.description,this.state.type,this.state.file);
}
});
}
OnConfigormalertMessage=()=>{
这是我的国家({
警报消息:“”,
成功:错,
警告:错误,
});
};
renderAlertMessage(){
var intl=this.props.intl;
const{alertSuccess,alertWarning,alertMessage}=this.state;
返回(
);
}
render(){
//const{getFieldDecorator}=this.props.form;
console.log(“gfg”,this.props.responseData)
常量formItemLayout={
labelCol:{
xs:{span:24},
sm:{span:24},
md:{span:12},
},
包装纸:{
xs:{span:24},
sm:{span:24},
md:{span:12},
},
};
常量tailFormItemLayout={
包装纸:{
xs:{span:24},
sm:{span:24},
md:{span:20},
},
};
返回(
Ajun Extrait MP3
gfdffd{this.props.responseData}

乳头

描述

类型

类型1 类型2 上传菲希尔MP3

{this.state.selectedFileName} 上传 {this.state.showPlayer? :null} 阿约特 {this.renderAlertMessage()} ); } } const AjoutExtraitForm=Form.create()(AjoutExtrait); 常量mapStateToProps=({mp3})=>{ 常数{ 响应数据 }=mp3; 返回{ 响应数据 } }; 导出默认连接(mapstatetops,{addMP3Action})(AjoutExtraitForm);

当我
console.log(this.props.responseData)
我没有定义时,你知道吗?

我相信你的问题是,在你的reducer中,
操作
没有属性
responseData
。请记住,您的操作将返回一个具有属性
type
有效负载
的对象。当您将其传递给reducer以更新状态时,您需要查看
action.payload
,以访问在操作中发送的数据

例如,您可能希望减速器看起来更像这样:

const INIT_STATE = {
    responseData: ''
  };

  export default (state = INIT_STATE, action) => {
    switch (action.type) {
      case ADD_MP3: {
        return {
          ...state,
          responseData: action.payload
        }

      }
      default:
        return state;
    }
  }
有关更多详细信息,请参阅文档: