首页 > 解决方案 > React.js 如何将数据从渲染传递到方法

问题描述

我想通过路由链接将数据从组件 A 传递到组件 B,然后在组件 B 中发出 API 请求,我能够将它从组件 A 传递到 B,但无法弄清楚如何从内部渲染传递该数据到将发出 API 请求的方法。希望我很清楚请看下面的代码。并提前感谢。

组分 A

<ul>
  {this.state.movies.map(movie => (
  <li key={movie.imdbID}>
   <img alt="img" src={movie.Poster} />
   <h1>{movie.Title}</h1>
   <p>{movie.Year}</p>
   <button>
   <Link to={{ pathname: "./productdetail", movieid: movie.imdbID }}>View More</Link></button>
  </li>))}
</ul>

B组份

class ProductDetailPage extends React.Component {
  state = {
    movieIdSearch: []
  };

  movieIdRequest(id) {
    axios.get(`http://www.omdbapi.com/?apikey=bcfe7e46&i=${id}`).then(res => {
      const movieById = res.data;
      this.setState({ movieIdSearch: movieById });
    });
  }

  render() {
    const {
      Poster,
      Title,
      Year,
      Released,
      Runtime,
      Genre,
      Country,
      Language,
      Actors,
      Plot
    } = this.state.movieIdSearch;
    return (
      <div>
        {/*how to pass   this.props.location.movieid to a movieIdRequest method*/}
        <img alt="img" src={Poster} />
        <h3>{Title}</h3>
        <div>
          <p>{Year}</p>
          <p>{Released}</p>
          <p>{Runtime}</p>
          <p>{Genre}</p>
          <p>{Country}</p>
          <p>{Language}</p>
        </div>
        <div>
          <h5>{Actors}</h5>
          <p>{Plot}</p>
        </div>
      </div>
    );
  }
}

标签: reactjsapireact-routercomponentsreact-component

解决方案


推荐阅读