Mysql 如何将许多组件中使用的功能转换为自己的组件,以便在整个应用程序中重用?

Mysql 如何将许多组件中使用的功能转换为自己的组件,以便在整个应用程序中重用?,mysql,reactjs,Mysql,Reactjs,我在多个页面上使用了一个fetch请求,并且希望将其转换为一个组件,以便在需要时调用它。事实证明,这比我想象的要困难得多,这带来了许多问题 我尝试过使用wrappedComponent函数,但不确定这是否是解决方案,因为它仍然不起作用。现在的意思是fetchPosts类构造函数不能在没有新函数的情况下调用 const that = this; fetch ('/testrouter') .then (response => {

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

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

        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中的另一个组件直接用它的名字来调用它。我尝试过这样做:

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(WrappedComponent){
类FetchPosts扩展组件{
建造师(道具){
超级(道具)
此.state={
员额:[]
}
}
fetchAllPosts(){
常数=this;
获取(“/testrouter”)
。然后(响应=>{
返回response.json();
}).然后(jsonData=>{
setState({posts:jsonData})
}).catch(错误=>{
console.log('Error fetch posts data'+err)
});
}
render(){
返回();
}
}
回帖;
}
导出默认回帖
然后导入它并用fetchPosts调用它,但它不起作用


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

您可能需要创建一个自定义挂钩来完成此操作:

useFetch.jsx

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
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}/> }
  </>)
}
MyComponent.jsx

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
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}/> }
  </>)
}
从“React”导入React
从“./useFetch.jsx”导入useFetch
常量MyComponent=()=>{
const data=useFetch(“/testrouter”)
返回(
{data.loading&&“loading…”
{data.error&&`fetch期间出错:{error.message}`}
{data.data&&}
)
}

使用一些全局状态管理、redux、上下文api等。