如何在 React 中使用 HOC 从链接到页面到父级的参数中获取 id 以获取数据

问题描述

##我没有在房间数据组件中获取数据#### ##我的HOC是## ##高阶函数用于从本地主机服务器获取数据,高阶组件适用于其他获取,但为此它不提供数据###

function withFetch(WrappedComponent,requestUrl) {    
  class WithFetch extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        data: [] ##this data is required in the child component###
      };
    }
    
    componentDidMount() {
      if (requestUrl) {
        this.fetchData(requestUrl);
      }
    }
    
    fetchData = async (requestUrl) => {
      this.setState({
        data: []
      });
      
      try {
        const response = await fetch(requestUrl);
        
        if (response.ok) {
          const data = await response.json();
          this.setState({
            data
          });  
        } else {
          throw new Error('Fetch request error');
        }
        
      } catch (err) {
        // handle an error
      }
    };
    
    render() {
      return (
        <WrappedComponent  {...this.state}
        {...this.props} />
      )
    }
  }
  
  return WithFetch; 
}

export default withFetch

##My App.js 父组件是###


  const RoomDataWithFetch = withFetch(
    RoomData,`http://localhost:3005/apiHost/${this.props.match.params.id}`
  );
const HomeWithFetch = withFetch(
    Home,'http://localhost:3005/apiHost'
  );
function App() {
  return (  
    <>
      <Route exact path='/' component={HomeWithFetch} />     
      <Route path='/room/:id' component={RoomDataWithFetch} />
    </>
  );
}

export default App;

###我的子组件在参数中具有 id###

export class RoomData extends Component {

    componentwillMount() {
        // When the component mounts 
        // call your action creator to load the details,// if songDetails are not already available
        if (!this.props.data) 
            this.props.data(this.props.match.params.id);
    }

    render() {
        return (
            <div>
                {console.log('props',this.props)}
            </div>
        )
    }
}

export default RoomData

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)