我在多个页面上使用了一个fetch请求,并希望将其转换为一个组件,以便在需要时随时调用它。事实证明,这比我想象的要难,而且它带来了许多问题。
我尝试过使用wrappedComponent函数,但不确定这是否是解决方案,因为它仍然不起作用。现在它说fetchPosts类构造函数不能在没有new的情况下被调用。
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调用它,但它不起作用。
我希望我能够创建一个组件,添加代码,然后导入组件,但这不起作用。
发布于 2019-05-31 03:28:27
您可能需要创建自定义钩子来执行此操作:
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
MyComponent.jsx
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}/> }
</>)
}
https://stackoverflow.com/questions/56378529
复制相似问题