从子组件访问父组件状态

时间:2018-09-03 09:05:23

标签: reactjs

我不知道如何从子组件访问父组件状态。当我在下面尝试我的代码时,我的父组件出现错误:

  

无状态功能组件不能具有引用。

有人可以指出正确的方向吗?

这是我的父组件(Podcast.js)

import React, { PureComponent } from 'react';
import PodcastItem from './PodcastItem';

class Podcast extends PureComponent { // PureComponent is preferred here instead of Component

  constructor(props) {
    super(props); 

    this.state = {
      podcast: []
    };
  }

  // Fetches podID from props.match
  fetchPodcast () {

    fetch(`https://itunes.apple.com/search?term=podcast&country=se&media=podcast&entity=podcast&limit=20`)
      .then(response => response.json())
      .then(data => this.setState({ podcast: data.results }));
  }

  componentDidMount () {
    this.fetchPodcast()
  }

  // Check if new props is not the same as prevProps
  componentDidUpdate (prevProps) {
    // respond to parameter change
    let oldId = prevProps.match.params.podID
    let newId = this.props.match.params.podID
    if (newId !== oldId)
      this.fetchPodcast()
  }

  render() {
    return (
      <div>
        <h2>Country ({this.props.match.params.podID}) </h2>
        <ul>
          {this.state.podcast.map(podcast => (
            <PodcastItem key={podcast.collectionId} podcast={podcast} />
          ))}
        </ul>
      </div>
    )
  }
}

export default Podcast;

这是子组件(PodcastItem.js)

import React from 'react';

// Here Stateless function is enough
const PodcastItem = ({ podcast }) => (
  <li key={podcast.collectionId}>
    <a ref={podcast.collectionId}>{podcast.collectionName}</a>
  </li>
);

export default PodcastItem;

0 个答案:

没有答案