Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

reactjs - Child component is not rendering props

I got a problem ChildComponent is not rendering data with map function, although console.log(data) prints the data every time I fetch APIs with a click in MainComponent.

On a click MainComponent should fetch APIs for all episodes for each character of Rick and Morty. handleClick method fetches multiple APIs, may be I am calling them wrong? Props are being updated with each click I can see it, but data is not rendered.

class MainComponent extends Component {
  constructor(props) {
    super(props);
    this.state = { actors: [], episodes: [] };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(arr) {
    const dataEpisodes = [];
    arr.map((api) =>
      axios.get(api).then((response) => dataEpisodes.push(response.data.name))
    );
    this.setState({ episodes: dataEpisodes });
  }

  componentDidMount() {
    axios
      .get("https://rickandmortyapi.com/api/character")
      .then((response) => this.setState({ actors: response.data.results }));
  }

  render() {
    console.log(this.state.episodes);
    return (
      <div className="container">
        <div className="row g-3">
          <div className="col-md-5 col-lg-4 order-md-last">
            <ChildComponent episodes={this.state.episodes} />
          </div>
          <div className="col-md-7 col-lg-8 ">
            <div className="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3">
              {this.state.actors.map((actor) => (
                <div key={actor.id} className="col m-3">
                  <div className="card shadow-sm">
                    <img
                      className="bd-placeholder-img card-img-top"
                      width="100%"
                      height="225"
                      src={actor.image}
                      role="img"
                      aria-label="Placeholder: Thumbnail"
                      preserveAspectRatio="xMidYMid slice"
                      focusable="false"
                    />

                    <div className="card-body">
                      <h1 className="card-text">{actor.name}</h1>
                      <div className="d-flex justify-content-between align-items-center">
                        <div className="btn-group">
                          <button
                            onClick={() => this.handleClick(actor.episode)}
                            type="button"
                            className="btn btn-sm btn-outline-secondary"
                          >
                            Episodes
                          </button>
                        </div>
                        <small className="text-muted">{actor.species}</small>
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default MainComponent;

and this is my ChildComponent

const ChildComponent = (props) => {
  const data = props.episodes;
  console.log(data);
  return (
    <div>
      <h1>Episodes</h1>
      {data.map((i) => (
        <h6>{i}</h6>
      ))}
    </div>
  );
};

export default ChildComponent;
question from:https://stackoverflow.com/questions/65940989/child-component-is-not-rendering-props

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your API calls are async and you need to wait for them to complete before setting the state. The correct way to implement the fetch call is to make use of Promise.all which waits for all promises to resolve.

handleClick(arr) {
    const dataEpisodes = [];
    const promises = arr.map((api) =>
      axios.get(api).then((response) => response.data.name)
    );
    Promise.all(promises).then(dataEpisodes => this.setState({ episodes: dataEpisodes }));
    
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...