对组件属性做出反应

时间:2018-06-30 10:04:57

标签: javascript reactjs async-await es2017

我有一个用于调用同步功能executeCode的组件。 问题是我的executeCode是异步函数,该函数返回truefalse,但是现在我的函数是异步的,我需要使用await来获取值,因为异步函数可以一个承诺。问题是我无法使用await,我尝试使用匿名函数或使用.then()进行诺言,但在这种情况下不适用,因为我需要立即提供该值。 executeCode现在处于异步状态,因为它需要进行其他操作。

executeCode = async ( methodCode ='', params = {} ) => {
  const result = await crudCode[methodCode](params);
  return result.valueToReturn;
};

render() {
  return (
    <Field
      name="datedeferred"
      component={FormField}
      executeCode={this.executeCode}
      typeInput="text"
      disabled={ 
        this.executeCode( 'onDisabled', { inputFullNameWithLine: 'datedeferred',formProps: this.props })
      }
    />
  );
}

1 个答案:

答案 0 :(得分:-1)

您可以在async中运行componentDidMount函数,然后将结果放入state中,并使用它。

示例

function someAsyncCheck() {
  return new Promise(resolve => setTimeout(() => resolve(true), 1000));
}

class App extends Component {
  state = { loading: true, disabled: false };

  async componentDidMount() {
    const result = await someAsyncCheck();
    this.setState({ loading: false, disabled: result });
  }

  render() {
    const { loading, disabled } = this.state;

    if (loading) {
      return null;
    }

    return <input disabled={disabled} />;
  }
}
相关问题