首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将在多个组件中使用的函数转换为自己的组件,以便在整个应用程序中重用?

如何将在多个组件中使用的函数转换为自己的组件,以便在整个应用程序中重用?
EN

Stack Overflow用户
提问于 2019-05-30 20:40:57
回答 1查看 15关注 0票数 -1

我在多个页面上使用了一个fetch请求,并希望将其转换为一个组件,以便在需要时随时调用它。事实证明,这比我想象的要难,而且它带来了许多问题。

我尝试过使用wrappedComponent函数,但不确定这是否是解决方案,因为它仍然不起作用。现在它说fetchPosts类构造函数不能在没有new的情况下被调用。

代码语言:javascript
复制
        const that = this; 
        fetch ('/testrouter')
        .then (response => {
            return response.json(); 
        }).then(jsonData => {
            that.setState({posts:jsonData})
        }).catch(err => {
            console.log('Error fetch posts data '+err)
        });
    }

这就是我想要转换成组件的东西,这样我就可以从componentDidMount中的另一个组件中按其名称调用它。我尝试过这样做:

代码语言:javascript
复制
function fetchPosts(WrappedComponent) {
    class FetchPosts extends Component {
     constructor(props) {
         super(props)
         this.state = {
             posts: []
         }
     }

     fetchAllPosts() {
         const that = this; 
        fetch ('/testrouter')
        .then (response => {
            return response.json(); 
        }).then(jsonData => {
            that.setState({posts:jsonData})
        }).catch(err => {
            console.log('Error fetch posts data '+err)
        });
    }
    render() {
        return (<WrappedComponent 
        fetchAllPosts = {this.fetchAllPosts})
        />);
    }

}
    return FetchPosts;

}


export default fetchPosts

然后导入它并使用fetchPosts调用它,但它不起作用。

我希望我能够创建一个组件,添加代码,然后导入组件,但这不起作用。

EN

回答 1

Stack Overflow用户

发布于 2019-05-31 03:28:27

您可能需要创建自定义钩子来执行此操作:

useFetch.jsx

代码语言:javascript
复制
import React, { useState, useEffect } from 'react'

const useFetch = (url) =>
  const [state, setState] = useState({ loading: true, data: null, error: null })

  useEffect(() => {
    fetch(url)
      .then(res => res.json())
      .then(data => setState(state => ({ ...state, loading: false, data }))
      .catch(error => setState(state => ({ ...state, loading: false, error }))
  },[])

  return state
}

export default useFetch

MyComponent.jsx

代码语言:javascript
复制
import React from 'react'
import useFetch from './useFetch.jsx'

const MyComponent = () => {
  const data = useFetch('/testrouter')

  return (<>
    { data.loading && "Loading..." }
    { data.error && `There was an error during the fetch: {error.message}` }
    { data.data && <Posts posts={data.data}/> }
  </>)
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56378529

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档