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

标签 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.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;
}

这是我的 reducer

  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 的响应的 View

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);

当我console.log(this.props.responseData)时,我得到了未定义,你有什么想法吗?

最佳答案

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

例如,您可能希望您的 reducer 看起来更像这样:

const INIT_STATE = {
    responseData: ''
  };

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

      }
      default:
        return state;
    }
  }

您可以随时引用文档了解更多细节: https://redux.js.org/basics/basic-tutorial

关于javascript - 在 React 中获取 POST API 的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58416520/

相关文章:

reactjs - 我的 React 应用程序正在使用 .env 文件中的值而不是 .env.local 文件

api - Hyperwallet API,删除用户/转账方式

javascript - 需要一个 javascript 正则表达式来匹配特定路径

javascript - 解析 CSV 而不下载/保存

javascript - Vue.js。在 get 函数中访问 axios

javascript - Mobx 更新对象中的单个属性

javascript - 在 React 中停止另一个函数的间隔

javascript - 三元运算符在 react js 渲染函数中不起作用

javascript - 使用 YouTube API v3 获取视频的完整描述

json - 验证 Node 中 swagger json.schema 的 POST 数据