【问题标题】:react await on component property对组件属性做出等待等待
【发布时间】:2018-12-09 08:46:15
【问题描述】:

我有一个组件用来调用同步函数executeCode。 我的executeCode 的问题是异步函数,这个函数返回truefalse,但是现在我的函数是异步的,我需要使用等待来获取值,因为异步函数给出了一个承诺。问题是我不能使用等待,我已经尝试了匿名函数或.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 })
      }
    />
  );
}

【问题讨论】:

    标签: javascript reactjs async-await ecmascript-2017


    【解决方案1】:

    您可以在 componentDidMount 中运行您的 async 函数并将结果放入 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} />;
      }
    }
    

    【讨论】:

    • 谢谢,但我无法更改逻辑,它很复杂,有 onchange 和 debounce 会不断修改状态,我的问题不是更改逻辑,而是管理 async 并在属性内等待
    • @DDave render 中不能有异步逻辑,这就是我更改逻辑的原因。那样做是根本不可能的。
    猜你喜欢
    • 1970-01-01
    • 2021-05-24
    • 2018-06-05
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 2018-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多