【问题标题】:How to use a callback in a render() of React component如何在 React 组件的 render() 中使用回调
【发布时间】:2020-11-08 20:11:36
【问题描述】:

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

服务器方法:

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 的值?

【问题讨论】:

    标签: reactjs meteor


    【解决方案1】:

    异步函数

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

    因此,如果您不熟悉 JavaScript 或异步行为,我建议您阅读 this excellent answer and explanation about the topic

    问题说明

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

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

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

    问题的解决方案

    这里的方法是使用 Reacts state,这正是这些场景。

    通过使用 state 和方法 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>
        );
      } 
    }
    

    我还使用了 React 的componentDidMount-Lifecycle-Method,因为它是触发 API 调用的推荐方式。您可以在official lifecycle documentation

    中阅读有关生命周期的更多信息

    这个组件的生命周期如下:

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

    【讨论】:

    • 非常感谢您清晰而出色的回答,它解决了我的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    • 1970-01-01
    • 2020-08-12
    • 1970-01-01
    • 2016-01-19
    相关资源
    最近更新 更多