我的项目正在多个文件中进行Axios调用,我想对其进行调制并将该调用作为道具传递给需要它的其他文件。
这是我的 componentDidMount()方法,该方法具有以下调用:
componentDidMount () {
document.body.style = 'background: #b8bab2;'
// Retrieve projects data
axios.get('/env?var=READER_HOSTNAME').then(response => {
return axios.get(`${response.data.var}/graphql?query=${queries.allProjects()}`)
}).then(response => {
this.setState({
projects: response.data.data.projects,
visible: response.data.data.projects,
isLoaded: true
})
})
}
答案 0 :(得分:-1)
您可以创建一个higher order component。
import React, { Component } from 'react'
export default withData = MyComponent => {
return class MyComponentWithData extends Component {
state = { projects: null, visible: null, isLoaded: false }
componentDidMount() {
// Retrieve projects data
axios.get('/env?var=READER_HOSTNAME')
.then(response => {
return axios.get(`${response.data.var}/graphql?query=${queries.allProjects()}`)
}).then(response => {
const { projects } = response.data.data
this.setState({
projects,
visible: projects,
isLoaded: true
})
})
}
render() {
const { projects, visible, isLoaded } = this.state
if (!isLoaded) {
return null
}
return (
<MyComponent
{...this.props}
projects={projects}
visible={visible}
isLoaded={isLoaded}
/>
)
}
}
}
将withData
导入要使用的组件中,如下所示:
class SomeComponent extends Component {
// ... component code
}
export default withData(SomeComponent)