在反应组件中获得承诺价值

时间:2017-02-17 22:09:42

标签: javascript reactjs promise

我的组件中有一个辅助函数。当我console.log(helperFunction())时,我会在控制台中看到它。

enter image description here

当我尝试将辅助函数添加到输入字段的值时。我明白了。

enter image description here

如何在输入中获得[[PromiseValue]]

  render() {
    console.log(getProjectName());
    return (
      <form ref={(input) => this.eventForm = input} onSubmit={(e) => this.createEvent(e)} className="slds-form">
        <div className="slds-form-element">
          <label className="slds-form-element__label">Assigned To</label>
          <div className="slds-form-element__control">
            <input ref={(input) => this.assigned = input} type="text" className="slds-input"  disabled/>
          </div>
        </div>
        <div className="slds-form-element">
          <label className="slds-form-element__label">Related To</label>
          <div className="slds-form-element__control">
            <input ref={(input) => this.related = input} type="text" className="slds-input" defaultValue={getProjectName()} disabled/>
          </div>
        </div>
        <div className="slds-form-element">
          <label className="slds-form-element__label">Subject</label>
          <div className="slds-form-element__control">
            <input ref={(input) => this.subject = input} type="text" className="slds-input"/>
          </div>
        </div>
        <div className="slds-form-element">
          <label className="slds-form-element__label">Location</label>
          <div className="slds-form-element__control">
            <input ref={(input) => this.location = input} type="text" className="slds-input" />
          </div>
        </div>
        <div className="slds-form-element">
          <label className="slds-form-element__label">Event Start</label>
          <div className="slds-form-element__control">
            <input ref={(input) => this.start = input} type="text" onChange={(e) => this.onChange(e)} className="slds-input" value={ this.state.start }/>
          </div>
        </div>
        <div className="slds-form-element">
          <label className="slds-form-element__label">Event End</label>
          <div className="slds-form-element__control">
            <input ref={(input) => this.end = input} type="text" onChange={(e) => this.onChange(e)} className="slds-input" value={ this.state.end } />
          </div>
        </div>
        <div className="slds-form-element">
          <label className="slds-form-element__label">Contact</label>
          <div className="slds-form-element__control">
            <input ref={(input) => this.contact = input} type="text" className="slds-input" disabled/>
          </div>
        </div>
        <button type="button" className="slds-button slds-button--neutral">Cancel</button>
        <button type="submit" className="slds-button slds-button--brand">Create</button>
      </form>
    );
  }

辅助功能

import axios from 'axios'

export function getProjectName() {

  return new Promise(function(resolve,reject){

  // gets the record id from the current url
  function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");

    for (var i=0;i<vars.length;i++) {
      var pair = vars[i].split("=");
      if(pair[0] == variable){return pair[1];}
    }

    return(false);
  }

  // used to access the rest api on my system
  const REST_API_URL = restApiUrl;
  const API_TOKEN = {
    headers: { "Authorization" : "Bearer " + sessionId,
              "Content-Type" : "application/json"
             }
  }
  const OPPORTUNITY_QUERY = "SELECT+Id,Name+FROM+OPPORTUNITY+WHERE+Id="

  // get projectId
  const id = getQueryVariable('projectId');

  // make requst for record name
  var request = axios.get(`${REST_API_URL}query/?q=${OPPORTUNITY_QUERY}'${id}'`,
     API_TOKEN
   ).then(function (response){
      return resolve(response.data.records[0].Name);
   })
  })
}

2 个答案:

答案 0 :(得分:8)

当处理render方法将使用的值并且也异步检索时,您应该在组件的状态中存在该值,并利用componentDidMount生命周期方法来检索值。

class SomeComponent extends React.component {
  constructor() {
    super();

    this.state = {
      projectName: ''
    }
  }

  componentDidMount() {
    // fetch the project name, once it retrieves resolve the promsie and update the state. 
    this.getProjectName().then(result => this.setState({
      projectName: result
    }))
  }

  getProjectName() {
    // replace with whatever your api logic is.
    return api.call.something()
  }


  render() {

    return (
      <input type="text" defaultValue={projectName}>
    )
  }
 }

你不想在render方法中调用函数并解析promise,因为render方法应该是基于state和props的纯函数。这是一个基本示例,但应该让您了解需要更改的内容。只需要将projectName设置为一个状态变量,并在第一个渲染中的componentDidMount中创建并解析它将等于一个空字符串,一旦它返回它将更新为api返回的任何内容。

如果您不希望在api调用结算之前显示输入,那么您可以添加其他检查以查看this.state.projectName是否等于任何内容,如果是,则呈现输入。

答案 1 :(得分:1)

您的代码存在问题。

<input ref={(input) => this.related = input} type="text" className="slds-input" defaultValue={getProjectName()} disabled/>

函数getProjectName返回一个promise,而不是该promise的已解析值。

您应该使用render()this.state中的this.props呈现您的用户界面,如果您有异步加载的数据,则可以将数据分配到{{1}使用this.props.relatedTo函数,在

行中
componentDidMount()

看看the state and lifecycle documentation