微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在 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 举报,一经查实,本站将立刻删除。