如何使用Hooks在React中显示/隐藏组件?

时间:2020-02-11 18:06:32

标签: javascript reactjs react-hooks

链接到CodeSandbox以了解我的意思。

当您单击播放器上的“查看配置文件”按钮时,该播放器的配置文件当前会加载到纸牌下方。这是因为Switch / Router语句位于卡的正下方,因此组件将在那里加载。

但是,我想要的是当某人单击播放器的“查看个人资料”按钮时,它加载了详细的个人资料,仅此而已。它当前确实可以导航到正确的路线,但是我只需要这些路线的详细资料。我不希望它加载所有三个玩家的卡片概述。

App.js(为了简洁起见,删除了样式化的组件):

import React, { useState, useEffect } from "react";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import { Container, Row, Col, Card } from "reactstrap";
import ReactDOM from "react-dom";
import axios from "axios";
import styled from "styled-components";
import { createGlobalStyle } from "styled-components";
import "bootstrap/dist/css/bootstrap.min.css";

import Intro from "./components/Intro";
import Tavares from "./components/Tavares";
import Matthews from "./components/Matthews";
import Marner from "./components/Marner";

import TavaresImg from "./img/tavares.jpg";
import MatthewsImg from "./img/matthews.jpg";
import MarnerImg from "./img/marner.jpg";

import "./styles.css";

function App() {
  // Set initial state for data
  const [data, setData] = useState({
    tavares: [],
    matthews: [],
    marner: [],
    tavaresFull: [],
    matthewsFull: [],
    marnerFull: []
  });

  // Fetch data
  useEffect(() => {
    const fetchData = async () => {
      // Grab all players API's
      let tavares =
        "https://statsapi.web.nhl.com/api/v1/people/8475166?expand=person.stats&stats=yearByYear,careerRegularSeason&expand=stats.team&site=en_nhlCA";
      let matthews =
        "https://statsapi.web.nhl.com/api/v1/people/8479318?expand=person.stats&stats=yearByYear,careerRegularSeason&expand=stats.team&site=en_nhlCA";
      let marner =
        "https://statsapi.web.nhl.com/api/v1/people/8478483?expand=person.stats&stats=yearByYear,careerRegularSeason&expand=stats.team&site=en_nhlCA";
      // Axios to get all api's
      axios
        .all([axios.get(tavares), axios.get(matthews), axios.get(marner)])
        .then(
          axios.spread((tavares, matthews, marner) => {
            console.log(tavares.data.people[0].stats[1].splits[0].stat);
            setData({
              tavares: [tavares.data.people[0]],
              matthews: [matthews.data.people[0]],
              marner: [marner.data.people[0]],
              tavaresFull: [tavares.data.people[0].stats[1].splits[0].stat],
              matthewsFull: [matthews.data.people[0].stats[1].splits[0].stat],
              marnerFull: [marner.data.people[0].stats[1].splits[0].stat]
            });
          })
        );
    };
    fetchData();
  }, []);

  return (
    <>
      <Router>
        <GlobalStyle />
        <Intro
          main="Maple Leafs API"
          text="Built with React, React Hooks, Styled Components and Axios
                consuming the NHL's REST API."
        />
        <Flex>
          <Container>
            <RowWrap>
              <Row>
                <Col lg="4">
                  <Image>
                    <img src={TavaresImg} alt="Tavares" />
                  </Image>
                </Col>
                <Col lg="8">
                  <CardBody>
                    {data.tavares.map(item => (
                      <>
                        <Title>
                          <h1>{item.fullName}</h1>
                        </Title>
                        <Number>{item.primaryNumber}</Number>
                        <p>{item.primaryPosition.name}</p>
                      </>
                    ))}
                    <ButtonLink>
                      <Link to="/tavares">
                        <button>View Profile</button>
                      </Link>
                    </ButtonLink>
                  </CardBody>
                </Col>
              </Row>
            </RowWrap>
            <RowWrap>
              <Row>
                <Col lg="4">
                  <Image>
                    <img src={MatthewsImg} alt="Matthews" />
                  </Image>
                </Col>
                <Col lg="8">
                  <CardBody>
                    {data.matthews.map(item => (
                      <>
                        <Title>
                          <h1>{item.fullName}</h1>
                        </Title>
                        <Number>{item.primaryNumber}</Number>
                        <p>{item.primaryPosition.name}</p>
                      </>
                    ))}
                    <ButtonLink>
                      <Link to="/matthews">
                        <button>View Profile</button>
                      </Link>
                    </ButtonLink>
                  </CardBody>
                </Col>
              </Row>
            </RowWrap>
            <RowWrap>
              <Row>
                <Col lg="4">
                  <Image>
                    <img src={MarnerImg} alt="Marner" />
                  </Image>
                </Col>
                <Col lg="8">
                  <CardBody>
                    {data.marner.map(item => (
                      <>
                        <Title>
                          <h1>{item.fullName}</h1>
                        </Title>
                        <Number>{item.primaryNumber}</Number>
                        <p>{item.primaryPosition.name}</p>
                      </>
                    ))}
                    <ButtonLink>
                      <Link to="/marner">
                        <button>View Profile</button>
                      </Link>
                    </ButtonLink>
                  </CardBody>
                </Col>
              </Row>
            </RowWrap>
          </Container>
        </Flex>
        <Container>
          <Row>
            <Col lg="12">
              <Switch>
                <Route
                  exact
                  path="/tavares"
                  component={() => (
                    <Tavares data={data.tavares} dataFull={data.tavaresFull} />
                  )}
                />
                <Route
                  exact
                  path="/matthews"
                  component={() => (
                    <Matthews
                      data={data.matthews}
                      dataFull={data.matthewsFull}
                    />
                  )}
                />
                <Route
                  exact
                  path="/marner"
                  component={() => (
                    <Marner data={data.marner} dataFull={data.marnerFull} />
                  )}
                />
              </Switch>
            </Col>
          </Row>
        </Container>
      </Router>
    </>
  );
}

export default App;

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

1 个答案:

答案 0 :(得分:1)

问题是您的常用组件,即仪表板页面是外部开关,因此每次必须渲染。为实现此目的,请制作另一个仪表板组件并将其链接到“ /”路由。 Check here and optimise