简体   繁体   English

如何在React中将单击的组件中的数据从一条路径传递到另一条路径?

[英]How do I pass data from a clicked component from one Route to another in React?

I'm working on a video game search app which fetches data from the GiantBomb API using React Router. 我正在开发一个视频游戏搜索应用程序,该应用程序使用React Router从GiantBomb API中获取数据。 When a search is done on the SearchGames component, it returns a list of games from the API through the Game component. 在SearchGames组件上完成搜索后,它会通过Game组件从API返回游戏列表。 What I'm stuck on is figuring out how to pass data details of a listed game you click to the GamesDetail component using Router. 我坚持要弄清楚如何使用路由器将单击的列出游戏的数据详细信息传递给GamesDetail组件。 I don't think I can do this using props since a separate view with all the details is neither a parent or a child component. 我认为我无法使用props来完成此操作,因为具有所有详细信息的单独视图既不是父组件也不是子组件。 I hope what I'm asking makes sense. 我希望我的要求是有道理的。

class App extends Component {
  render() {
    return (
      <Router>
        <div className="App">
          <Nav />
          <div className="container">
            <Switch>
              <Route exact path="/" component={MainPage} />
              <Route exact path="/games" component={GameSearch} />
              <Route exact path="/about" component={About} />}
              <Route exact path="/details" component={GamesDetails} />}
            </Switch>
          </div>
        </div>
      </Router>
    );
  }
}

class Search extends Component {
      constructor(props) {
        super(props);
        this.state = {
          title: "",
          games: []
        }
      }

  updateInput = (event) => {
    this.setState({
      title: event.target.value
    });
  }

  handleGames = (search) => {
    const proxyUrl = "https://cors-anywhere.herokuapp.com/";
    const key = "8cd10a7136710c1003c8e216d85941ace5a1f00e";
    const endpoint = `https://www.giantbomb.com/api/search/?api_key=`;
    const url = proxyUrl + endpoint + key + `&format=json&resources=game&query=${search}&limit=30`;

    fetch(url)
      .then(res => res.json())
      .then(data => {
        const response = data.results;
        console.log(response);
        response.forEach(game => {
          this.setState(prevState => ({
            games: prevState.games.concat(game)
          }))
        });
      });

    this.setState({
      games: []
    })

  }

  handleSubmit = (e) => {
    const { title } = this.state;

    e.preventDefault();

    if (!title) {
      return;
    } else {
      this.handleGames(title);
    }

  }

  render() {
    const { games } = this.state;
    return (

      <div className="App">
        <div className="search-bar">
          <form>
            <input
              className="input-field"
              type="text"
              placeholder="Search Game"
              onChange={this.updateInput}
            />
            <button
              className="search-button"
              onClick={this.handleSubmit}
            >Search</button>
          </form>
        </div>
        <div className="container">
          {games.length > 0 ? (
            games.map(game => {
              return <Game
                key={game.id}
                icon={game.image.icon_url}
                gameTitle={game.name}
              />
            })
          ) : (
              console.log(this.state.title)
            )
          }


        </div>
      </div>

    );
  }
}

const Game = (props) => {
  const { icon, gameTitle } = props;
  return (
    <div className="games-container">
      <div className="game-box">
        <img src={icon} alt="icon" />
        <Link to="/details">
          <p><strong>{gameTitle}</strong></p>
        </Link>
      </div>
    </div>
  );
}

const GameDetails = (props) => {
  const { icon, release, genres, summary} = props;
  return (
    <div className="details-content">
      <div className="box-art">
        <img src={icon} alt="box art" />
      </div>
      <div className="game-info">
        <h1>Game Details</h1>
        <div className="release-date">
          <h3>Release Data</h3>
          <p>{release}</p>
        </div>
        <div className="genres">
          <h3>Genres</h3>
          <p>{.genres}</p>
        </div>
        <div className="summary">
          <h3>Summary</h3>
          <p>{summary}</p>
        </div>
      </div>
    </div>
  );
}

You should be able to achieve this using Link with to as an object , which exposes a state than can be passed to the resulting Route : 您应该能够使用Link with to作为对象来实现此目的 ,该对象公开的state要比可以传递给结果Route

// ...
// pass game object to Game component
// if you are passing game, you probably don't need other props explicitly passed
{games.length > 0 ? (
  games.map(game => {
    return <Game
      key={game.id}
      game={game}
      icon={game.image.icon_url}
      gameTitle={game.name}
    />
  })
 ) : (
   console.log(this.state.title)
 )
}

// ...

const Game = (props) => {
  const { icon, gameTitle, game } = props;

  return (
    <div className="games-container">
      <div className="game-box">
        <img src={icon} alt="icon" />
        <Link to={{ pathname: "/details", state: { game } }}>
          <p><strong>{gameTitle}</strong></p>
        </Link>
      </div>
    </div>
  );
}

You can then access this state from prop location that react-router-dom injects into props : 然后,您可以从prop- 位置访问此state ,该位置react-router-dom注入props

const GamesDetails = (props) => {
  const { image: { icon_url: icon }, release, genres, summary } = props.location.state.game;

  return (
    <div className="details-content">
      <div className="game-info">
        <h1>Game Details</h1>
        <div className="box-art">
          <img src={icon} alt="box art" />
        </div>
        <div className="release-date">
          <h3>Release Data</h3>
          <p>{release}</p>
        </div>
        <div className="genres">
          <h3>Genres</h3>
          <p>{genres}</p>
        </div>
        <div className="summary">
          <h3>Summary</h3>
          <p>{summary}</p>
        </div>
      </div>
    </div>
  );
}

Here is an example in action. 这是一个实际的例子

Hopefully that helps! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将数据从一个组件实时传递到另一个组件? - How do i pass data from one component to another in realtime? 如何在 React.JS 中将数据从一个组件传递到另一个组件 - How to pass data from one component to another in React.JS React:如何从一个组件获取API数据并将其传递给另一组件 - React: How to get API data from one component and pass it to another 如何在 React Native 中将数据从一个组件传递到另一个组件 - How to pass data from one component to another in react native 如何将 state 从一条反应路线传递到另一条反应路线? - How can i pass a state from one react route to another react route? React - 如何将 API 数据从一个组件传递到另一个 js 文件中的另一个组件? - React - How can I pass API data from one component to another in a different js file? 如何使用 React 将数据从列表传递到另一个组件? - How can I pass a data to another component from a list with React? 如何将 useState 从一个组件传递到另一个组件? - How do I pass useState from one component to another? 如何将变量从一个组件传递到另一个组件? - How do I pass a variable from one component to another? 如何以角度将数据从一个组件传递到另一个组件(新浏览器选项卡)? - How do I pass data from one component to another (New Browser Tab) in angular?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM