繁体   English   中英

反应等待组件属性

[英]react await on component property

我有一个用于调用 sync function executeCode的组件。 问题是我的executeCode是异步 function,这个函数返回truefalse ,但现在我的 function 是异步的,我需要使用 await 来获取值,因为异步函数给出 promise。问题是我不能使用 await ,我已经尝试使用 .then .then()匿名 function 或 promise 但它不适用于这种情况,因为我立即需要该值。 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 })
      }
    />
  );
}

在您在伪代码中使用的示例中,每当触发重新渲染时,都会调用异步 function 但渲染取决于结果 - 所以一个人进入了死胡同。 一种解决方案是观察相关变量的变化,然后触发异步变化。 获取异步的结果并设置一个 state 托管变量。 React 将获取托管变量的变化并触发重新渲染。 见下文。


const [buttonDisabled, setButtonDisabled] = useState<boolean>(false)

useEffect(() => {
  someAsnycCheck().then(result => setButtonDisabled(result));
},[params])

return (
  <button disabled={buttonDisabled}...>
)

这基本上意味着:观察params的变化,然后调用异步 function。当结果到达时,将buttonDisabled设置为结果。

您可以在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} />;
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM