代码之家  ›  专栏  ›  技术社区  ›  DDave

响应等待组件属性

  •  0
  • DDave  · 技术社区  · 8 年前

    我有一个组件用来调用同步函数 executeCode . 问题是我的 执行代码 是异步函数,此函数返回 true 或 false ,但是现在我的函数是异步的,我需要使用wait来获取值,因为异步函数给出了一个承诺。问题是我不能使用wait,我尝试了匿名函数或承诺 .then() 但在这种情况下它不适用,因为我需要即时的值。 执行代码 现在是异步的,因为其他操作需要它。

    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 回复  |  直到 8 年前
        1
  •  -1
  •   Tholle    8 年前

    你可以运行你的 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} />;
      }
    }