我有一个HOC
要使用axios
处理加载,
这是withAxiosHOC
的代码:
export default (url, WrapComponent) => {
return class extends React.Component {
constructor(props) {
super(props);
this.state = {
data: null,
isLoading:false,
isFailed:false,
isError:false,
message:null,
};
}
componentDidMount(){
this.callAPI()
}
async callAPI(){
//show loading
// handle API and pass to wrapped component
// hide loading
}
render() {
if (this.state.isLoading) {
return (
//show loading UI
)
} else if(this.state.isFailed){
return(
//show Failed UI
)
} else if(this.state.isError){
return(
//show Error UI
)
}
return (
<WrapComponent data={this.state.data} {...this.props} />
)
}
}
}
通常我经常这样使用HOC
,比方说Home.js
:
export default withAxiosHttp(
'https://reactnative.dev/movies.json',
class Home extends React.Component{
constructor(props) {
super(props);
this.state = {
data:props.data
}
}
render() {
return(
<View style={{flex:1, backgroundColor:Color.black}}>
<MyText>{JSON.stringify(this.state.data, null, 2)}</MyText>
</View>
)
}
}
)
但是有时候我需要根据包装组件的状态来调用URL,
类似Suggestion.js
的东西:
export default withAxiosHttp(
'https://exampleAPIneedDynamicValue.com/suggestion?lat='+this.state.position.lat+'&long='+this.state.position.long,
class Suggestion extends React.Component{
constructor(props) {
super(props);
this.state = {
data:props.data,
position:{lat:null, long:null}
}
}
componentDidMount(){
let tempPosition = this.state.position
tempPosition.lat = MyLatitude
tempPosition.long = MyLongitude
this.setState({position:tempPosition})
}
render() {
return(
<View style={{flex:1, backgroundColor:Color.black}}>
<MyText>{JSON.stringify(this.state.data, null, 2)}</MyText>
</View>
)
}
}
)
正如您在Suggestion.js
中看到的那样,我需要根据lat
的{{1}}和long
调用URL,
和position state
仅在lat long state
的{{1}}中可用,
我的问题:
wrappedComponent
状态可用时,如何处理HOC来运行?HOC
?请给我一个在
lat long
范围内的建议/答案
答案 0 :(得分:0)
您可以将url
参数修改为函数而不是字符串。
在withAxiosHOC
async callAPI(){
axios.get(url(this.state)).then(data => {
//logic here
})
}
您的Suggestion.js
将
export default withAxiosHttp(
(state) => {
return 'https://exampleAPIneedDynamicValue.com/suggestion?lat='+state.position.lat+'&long='+state.position.long
},
class Suggestion extends React.Component{
constructor(props) {
super(props);
this.state = {
data:props.data,
position:{lat:null, long:null}
}
}
componentDidMount(){
let tempPosition = this.state.position
tempPosition.lat = MyLatitude
tempPosition.long = MyLongitude
this.setState({position:tempPosition})
}
render() {
return(
<View style={{flex:1, backgroundColor:Color.black}}>
<MyText>{JSON.stringify(this.state.data, null, 2)}</MyText>
</View>
)
}
}
)