在React(Flux)中重用具有不同状态的提取 [英] Reusing Fetch with Different Pieces of State in React (Flux)

查看:32
本文介绍了在React(Flux)中重用具有不同状态的提取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有此功能,该功能位于我想重用的顶级组件中,但处于其他状态.在下面的代码示例中,我在userData上使用了它,但是我希望能够在状态为repoData的状态下重用它,既可以在其子组件内,也可以在外部.只是不确定如何去做,因为如果我做类似将状态传递为args的事情,则将状态设置为会引发错误,因为它看起来像这样:this.setState({this.state.userData:data}) .

I have this function that is in the top level component that I'd like to reuse but on a different piece of state. In the following code sample, I'm using it on userData, but I'd like to be able to reuse it on a piece of state called repoData, either within the same component it's child, or outside. Just not sure how to go about it, since, if I do something like pass it the states as args, setting the state would throw an error because it would look like: this.setState({this.state.userData: data}).

    fetchUserData(params) {
        fetch('https://api.github.com/users/' + params)
        .then(response => {
          if (!response.ok) {
            throw Error("Network failure")
          }
        return response;
        })
      .then(data => data.json())
      .then(data => {
        this.setState({
          userData: data
        })
      }, () => {
        this.setState({
            requestFailed: true
        })
      })
  }

推荐答案

我相信您的问题更多是关于重构代码.在这里,您可以将其视为异步获取用户数据的逻辑.您的组件不需要知道谁(fetchaxios)正在为其获取数据.同样,组件也不需要从哪里知道(https://api.github.com/users/' + params)来获取此数据.
一种可行的实现方式是将fetch调用移到一个单独的函数中,该函数将在异步获取数据后将数据返回到您的组件.然后,组件负责以所需的方式处理数据.
因此,正如您所看到的,关键是识别并分离出每段代码的职责.这样做的好处是代码结构清晰,行数少,可维护的代码以及最重要的是易于测试的代码.
我希望这能解决您的问题.如果您有兴趣进一步了解此类技术,则可以阅读 DRY原理重构技术.

Your question is more about refactoring your code I believe. Here you can look at it as moving out the logic of fetching user data asynchronously. Your component need not know who(fetch, axios) is doing the work of fetching the data for it. Also it is not required for a component to know from where(https://api.github.com/users/' + params) to get this data.
One possible way of doing it is to move your fetch call in a separate function which will return the data to your component after fetching it asynchronously. Then it is responsibility of component to handle the data the way it want to.
So as you can see the key point here is identifying and separating out the responsibilities of each piece of code. Advantages of doing this will be clean code structure, less number of lines, maintainable code and most importantly easily testable code.
I hope this solves your problem. If you are interested to learn about such techniques more you can read about DRY principle and refactoring techniques.


我已创建此代码示例供您参考

Edit 1:
I have created this code sample for your reference

什么是JavaScript承诺: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise
一些获取示例: https://davidwalsh.name/fetch
我个人建议使用axios.您可以在此处查看fetch和axios的比较: https://medium.com/@thejasonfile/fetch-vs-axios-js-for-making-http-requests-2b261cdd3af5

What are JavaScript Promises: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
Some samples for fetch: https://davidwalsh.name/fetch
I personally recommend using axios. You can see comparison of fetch and axios here: https://medium.com/@thejasonfile/fetch-vs-axios-js-for-making-http-requests-2b261cdd3af5

这篇关于在React(Flux)中重用具有不同状态的提取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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