从 React 外部更新组件状态(在服务器响应上) [英] Update component state from outside React (on server response)

查看:39
本文介绍了从 React 外部更新组件状态(在服务器响应上)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 React.目前我有几个 components 作为父子链接,通过回调可以轻松完成它们之间的通信.

I'm in the process of learning React. At the moment I have several components chained as parent-child, communication across them is done easily with callbacks.

我有一个表格(反应组件)和一个小的模态ajax表单(无反应).当我收到来自服务器的响应(一个项目)时,我想将该项目添加到表格中.

I have a table (react component) and a small modal ajax form (no react). When I receive the response (an item) from the server I would like to add the item to the table.

我的主要问题是,是否可以从外部反应(在本例中为服务器响应)触发组件状态更改?

My main question is, is it possible to trigger a component state change from outside react (in this case on server response)?

推荐答案

你能在组件外触发组件状态改变吗?

Can you trigger a component state change outside a component?

是的.这是一个简单的例子

在你的 React 组件中设置一个全局可用的闭包,它会在函数被触发时更新它的状态.

In your react component set up a globally available closure which will update it's state when the function is fired.

componentDidMount(){
 globalVar.callback = (data) => {
    // `this` refers to our react component
    this.setState({...});     
  };
}

然后当您的ajax响应返回时,您可以使用返回的数据触发事件

Then when your ajax'd response comes back you can fire the event with the returned data

globalVar.callback(data);

或者对于更强大的东西,使用 自定义事件或订阅

Or for something more robust, use a custom event or subscription

这篇关于从 React 外部更新组件状态(在服务器响应上)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆