【发布时间】:2023-03-04 02:04:01
【问题描述】:
我有一个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 中看到的,我需要根据position state 的lat 和long 调用一个URL,
而lat long state 仅适用于wrappedComponent 的HOC,
我的问题:
- 当
lat long状态在 WrappedComponent 中可用时,我如何处理 HOC 以运行? - 我的 HOC 也可以用于
POST method吗?
请在
React Native范围内给我一个建议/答案
【问题讨论】:
标签: javascript reactjs react-native high-order-component