reactjs - 如何在 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的值?
解决方案
异步函数
在我回答这个问题之前,了解 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>
);
}
}
我还使用了componentDidMount
React 的 -Lifecycle-Method,因为它是触发 API 调用的推荐方式。您可以在官方生命周期文档中阅读有关生命周期的更多信息
该组件的生命周期将如下所示:
- 组件将被创建,构造函数将为
this.state
render()
方法被调用this.state.loading === false
- 因此内容将默认为字符串“正在加载...”- 该
componentDidMount()
函数被调用并将触发您的 API-Call - 您的回调被调用并执行
setState()
,将响应数据放入this.state
- 现在 react 知道状态已更改,它
render()
再次调用该方法。但这一次,this.state.loading === true
有一些价值this.state.opcion
- 因此内容将是您响应的价值。
推荐阅读
- java - 尝试在 java 上创建新文件时的 filenotFound
- r - 用 plotly 创建一个稍微重叠的条形图
- firebase - 如何返回未来
- > 从列表
>? - mysql - 如何选择列的每个不同值的最新记录
- kdb - 如何在 KDB 中将列表转换为矩阵?
- npm - 我可以在一个项目中独立安装两个 packages.json 吗?
- scala - 通过修改其私有方法来自定义 Spark ML 估计器(例如 GaussianMixture)的正确方法?
- python - 从 pikepdf 发送 pdf 作为 BytesIO 流-flask send_file 内容长度不匹配
- laravel - CORS 预检请求错误:预检请求不允许重定向
- java - 创建一个有效的“输入代码”字段(Java)