0

##我没有在房间数据组件中获取数据#### ##我的 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
4

0 回答 0