【问题标题】:Get axios call in reactjs在 reactjs 中获取 axios 调用
【发布时间】:2020-09-21 02:40:55
【问题描述】:

以下是我在调用 get 后得到的响应:

{
    "id": “12345”,
    “details”: {
        “name”: “sample doc”,
        “market: “sample market”
    }
}

我的服务方式:

ENDPOINTS = {
    product: "/market/product", 
}
     getDetails(
            id: string
          ): Promise<{
            id: string;
          }> {
            const url = `${this.ENDPOINTS.PRODUCT}/${id}/name`;
            return http
              .get(url)
              .then((response) => {
                return response.data;
              })
              .catch((error) => {
                throw error;
              });
          }

我的组件方法:

getTestingDone = () => {
    this.sampleService
      .getDetails(
        this.props.product.id,
      )
      .then((response) => {
        this.setState({
        });
      })
      .catch((error) => {
        console.log(error);
      });
  };

        <TextInput
          labelText="name"
          type="text"
          name="keyname"
          value = {name}
        />

我想在此输入字段中打印响应。不确定如何从服务器获得对 UI 的响应。谁能帮我解决这个问题。我需要做一个模型课吗?并在服务方法中返回它作为响应?

【问题讨论】:

    标签: javascript reactjs typescript axios


    【解决方案1】:
    constructor() {
      this.state = {
        name: ''
      }
    }
    
    getTestingDone = () => {
      this.sampleService
        .getDetails(this.props.product.id)
        .then(({details: {name}}) => {
          this.setState(state => ({...state, name}));
        })
    }
    
    render() {
      const { name } = this.state;
    
      return <TextInput
        labelText="name"
        type="text"
        name="keyname"
        value = {name}/>
    }
    

    【讨论】:

    • 我将从那里获得您在 .then() 中发送的详细信息。是模型类吗?
    • return response.data; in then getDetails 函数返回 json 响应,then(({details: {name}}) 破坏模型
    • 没看懂,能详细点吗
    【解决方案2】:

    这是上述问题的正确答案:

    constructor(){
        this.state = {
         details: {
              name: "",
              market: "",
            }
        }
    
        getTestingDone = () => {
          this.sampleService
            .getDetails(this.props.product.id)
            then((response) => {
                this.setState({
                  credentials: response.credentials,
                });
            })
    
          return <TextInput
            labelText="name"
            type="text"
            name="keyname"
            value = {this.state.details.name}/>
        }
        }
    

    【讨论】:

      猜你喜欢
      • 2020-07-17
      • 1970-01-01
      • 2023-02-01
      • 2019-05-02
      • 1970-01-01
      • 2021-02-07
      • 2020-01-25
      • 1970-01-01
      • 2019-03-03
      相关资源
      最近更新 更多