它是否被认为是 React Component 中的反模式解决承诺? [英] Is it considered anti-pattern resolve promises in React Component?

查看:35
本文介绍了它是否被认为是 React Component 中的反模式解决承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在应用程序的许多地方,我们确实调用了 /search api,您可以从结果中选择 id,然后结果将被丢弃,由于结果是暂时使用的,这让我觉得保存它们甚至调度操作都不值得(除了设置 isLoading 标志).但它会迫使我解决反应组件中的承诺,这被认为是不好的做法还是反模式?

In many places of the app we do call a /search api where you pick the id from of the result and the then the result will be discarded, Since the results are for temporal use, this makes me feel it's not worth to save them or even to dispatch actions (except to set a isLoading flag). But it will force me to resolve the promises in react components, is it considered bad practice or anti-pattern?

例如:

componentDidMount() {
    this.props.doSearch(criterias)
      .then(res => this.setState({ results: res.results }) )
  }

推荐答案

是的,这是 ReactJS 中已知的反模式,因为您不能保证在 promise 解析时组件仍然存在.从技术上讲,您可以使用 this.isMounted 进行检查,但这也被视为一种反模式.

Yes, this is a known anti-pattern in ReactJS, because you can't guarantee that the component will still exist when the promise resolves. You can technically check using this.isMounted, but that's also considered an anti-pattern.

问题是 ReactJS 并没有真正设计成一个完整的应用程序框架 - 当它实际上只是一个 V 时,你有点将 MVC 推入其中.为了最有效,React 应该与其他一些框架搭配使用可以存储应用数据的库(Redux 非常流行),然后 React 可以为您呈现.最好将 React 视为将内部 UI 状态转换为实际 UI 的库.不利于管理状态.

The problem is that ReactJS isn't really designed to be a full-on application framework - you're kind of shoving MVC into it when really it's only a V. To be most effective, React should be paired with some other library (Redux is very popular) which can store the application data, then React can present it for you. It's best to think of React as a library which turns the internal UI state into an actual UI. It's not good for managing state.

参见 https://facebook.github.io/react/blog/2015/12/16/ismounted-antipattern.html.

这篇关于它是否被认为是 React Component 中的反模式解决承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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