首页 > 解决方案 > 如何在 React 组件的 render() 中使用回调

问题描述

我想使用对集合进行计数的服务器方法的结果在反应组件的渲染方法中显示它。我知道我必须从回调函数中执行此操作,但它对我不起作用。

服务器方法:

export const analysis = new ValidatedMethod({
  name: "analysis",
  validate: new SimpleSchema({
    codigo: {
      type: String
    },
    rta: {
      type: String
    }
  }).validator(),
  run(one) {
    const rta = Respuesta.find({
      codigo: one.codigo,
      rtatexto: one.rta,
      activo: true
    }).count();
    console.log(rta);
    return Number(rta);
  }
});

来自客户的电话:

export default class AnalysisFila extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    const one = { codigo: this.props.codigo, rta: this.props.opcion };
    const rta = analysis.call(one, (err, res) => {
      return (
        <Table.Row>
          <Table.Cell> {this.props.opcion} </Table.Cell>
          <Table.Cell> {res} </Table.Cell>
        </Table.Row>
      );
    });
  }
}

如何在组件的渲染方法中使用res的值?

标签: reactjsmeteor

解决方案


异步函数

在我回答这个问题之前,了解 JavaScript 中同步函数和异步函数之间的区别很重要。

因此,如果您是 JavaScript 或异步行为的新手,我建议您阅读有关该主题的出色答案和解释

问题说明

这里的问题是 React 的render()方法是一个同步方法,这意味着 React 需要一个同步的返回值 with jsx(或 a React.Element)。

对于 React,您当前的渲染函数实际上不返回任何内容或undefined,因为您没有同步return语句。所以什么都不会被渲染。

React 无法知道您的回调何时被调用或返回什么,因为它完全在 Reacts 上下文之外执行。

问题的解决方案

去这里的方法是使用 Reacts状态,它正好适用于这些场景。

通过使用 state 和 method setState(),您可以在 API 的响应传递数据后立即异步触发要再次调用的渲染方法。此外,使用this.state,您可以将响应数据带入 react-context 并让它知道它。

一个完整的示例可能如下所示:

export default class AnalysisFila extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loaded: false
      opcion: {}
    };
  }

  componentDidMount() {
    const one = { codigo: this.props.codigo, rta: this.props.opcion };
    const rta = analysis.call(one, (err, res) => {
      this.setState({
        loaded: true,
        opcion: res
      }
    });
  }

  render() {
    const content = this.state.loaded ? this.state.opcion : 'Loading...';
    return (
     <Table.Row>
        <Table.Cell> {this.props.opcion} </Table.Cell>
        <Table.Cell> {content} </Table.Cell>
      </Table.Row>
    );
  } 
}

我还使用了componentDidMountReact 的 -Lifecycle-Method,因为它是触发 API 调用的推荐方式。您可以在官方生命周期文档中阅读有关生命周期的更多信息

该组件的生命周期将如下所示:

  1. 组件将被创建,构造函数将为this.state
  2. render()方法被调用this.state.loading === false- 因此内容将默认为字符串“正在加载...”
  3. componentDidMount()函数被调用并将触发您的 API-Call
  4. 您的回调被调用并执行setState(),将响应数据放入this.state
  5. 现在 react 知道状态已更改,它render()再次调用该方法。但这一次,this.state.loading === true有一些价值this.state.opcion- 因此内容将是您响应的价值。

推荐阅读