React.js如何将数据从父组件传递到子组件

时间:2019-01-25 15:14:02

标签: reactjs reactive-programming react-props react-component pass-data

我正在尝试通过搜索和ID提出API请求,并希望将该ID传递给另一个组件,当单击按钮时,该组件将在另一个页面中显示ID数据,但是我无法将该数据传递给另一个组件,请有人帮我解决这个问题,我正在尝试学习React并进行了很多研究,但找不到解决方案。将数据从父母传递给孩子,反之亦然,这使我感到困惑。任何帮助将不胜感激。

父组件

import React from "react";
import axios from "axios";
import { Link } from "react-router-dom";
import ProductDetailPage from "./productdetailpage";

class ProductLists extends React.Component {
  state = {
    movies: [],
    name: "",
    para: "No Data"
  };

  onchange = event => {
    this.setState({ name: event.target.value });
  };

  onsubmit = event => {
    event.preventDefault();
    const nameValue = this.state.name;
    axios
      .get(`http://www.omdbapi.com/?apikey=bcfe7e46&s=${nameValue}`)
      .then(res => {
        const movies = res.data.Search;
        this.setState({ movies });
      });
  };

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

      //below i'm trying to pass the movieId into other component
      const moviedata = <ProductDetailPage passMovieId={movieId} />;
      console.log(moviedata.props);
    });
  };

  render() {
    return (
      <div>
        <form onSubmit={this.onsubmit}>
          <input
            type="text"
            placeholder="Search Movie"
            onChange={this.onchange}
          />
        </form>
        {this.state.name === "" ? (
          <h1>No Data</h1>
        ) : (
          <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 onClick={() => this.viewDetail(movie.imdbID)}>
                  <Link to="./productdetail">View More</Link>
                </button>
              </li>
            ))}
          </ul>
        )}
      </div>
    );
  }
}
export default ProductLists;

子组件

import React from "react";

class ProductDetailPage extends React.Component {
  render() {
    return (
      <ul>
        <li>
          <img alt="img" src={this.props.movieId.Poster} />
          <h1>{this.props.movieId.Title}</h1>
          <p>{this.props.movieId.Plot}</p>
        </li>
      </ul>
    );
  }
}

export default ProductDetailPage;

1 个答案:

答案 0 :(得分:0)

您可以在链接中传递ID并在其中移动viewDetail函数:

    <Link movieId={movie.imdbID} to="./productdetail">View More</Link>

那么它应该作为该组件中的道具进行访问:

https://reacttraining.com/react-router/web/api/Link/others

相关问题