【问题标题】:Page not reloading in react?页面没有在反应中重新加载?
【发布时间】:2021-09-12 06:00:31
【问题描述】:

我面临路由 dom 错误。类别网址重定向正确,但内容没有重新加载我错过的内容,请告诉我您的反馈。我在下面提到 菜单.jsx 链接标签 url {x.category_url} 它确实改变了 url 但它没有改变页面的内容。 App.jsx line Route path="/category/:name/:id" component={CategoriesList}

App.jsx:

    // import logo from './logo.svg';
    import './App.css';
    import { BrowserRouter, Switch, Route } from 'react-router-dom';
    import CategoriesList from './ComponentList/CategoriesList'; 
    import CustomerReview from './StoreComponent/CustomerReview';
    import Related from './StoreComponent/Related'; 
import Home from './ComponentList/Home'; 
    import Store from './StoreComponent/Store';
    function App() {
      
      // const reload = () => window.location.reload();
      return (
        <BrowserRouter>
    
        <Switch>
          <Route exact path="/">
              <Home/>
            </Route>
            
            <Route path="/store/:name/:id" component={Store}>
              <Store/>
            </Route>
            <Route path="/store/:name/:id" component={CustomerReview}>
              <CustomerReview/>
            </Route>
            <Route path="/store/:name/:id" component={Related}>
              <Related/>
            </Route>
            
            <Route path="/category/:name/:id" component={CategoriesList}>
              <CategoriesList/>
            </Route>
           </Switch>
      </BrowserRouter>
        )
    }
    
    export default App;
Menu.jsx:
import React, { Component } from "react";
import { Grid, Image } from "semantic-ui-react";
import { Link } from "react-router-dom";
export default class Menu extends Component {
  constructor(props) {
    super(props);

    this.state = {
      data: [],
      isLoading: true,
    };
  }
  refreshPage() {
    window.location(false);
  }
  async componentDidMount() {
    const requestOptions = {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ title: "React POST Request Example" }),
    };

    const url = "http://localhost:3000/api/v4/web/categories";
    fetch(url, requestOptions)
      .then((response) => response.json())
      .then((json) => {
        this.setState({ data: json.categories });
        // console.log(json.categories)
      })
      .catch((error) => console.error(error))
      .finally(() => {
        this.setState({ isLoading: false });
      });
  }

  render() {
    // console.log(this.pathname)
    return (
      <Grid className="home-icon">
        <Grid.Row centered doubling columns={8} mobile>
          {this.state.data.map((x, i) => (
            <Grid.Column centered key={i}>
              <Link to={x.category_url}>
                <Image src={x.image} alt="" />
              </Link> 
              <Link to={x.category_url}>
                <p>{x.store_name}</p>
              </Link>
            </Grid.Column>
          ))}
        </Grid.Row>
      </Grid>
    );
  }
}
 CategoriesList.jsx:
import React, { Component, Fragment } from "react";
import { withRouter, Link } from "react-router-dom";
import { Grid, Image, Segment, Card } from "semantic-ui-react";
import TopMenuStrip from "../ComponentList/TopMenuStrip";
import LogoSection from "../ComponentList/LogoSection";
import Footer from "../ComponentList/Footer";
import Menu from "../ComponentList/Menu";
import CopyRight from "../ComponentList/CopyRight";
class CategoriesList extends Component {
  constructor(props) {
    super(props);

    this.state = {
      data: [],
      isLoading: true,
    };
  }

  async componentDidMount() {
    // console.log(this.props.match.params.id)
    let url_id = this.props.match.params.id;
    console.log("category");
    console.log(url_id);
    const url = "http://localhost:3000/api/v4/web/list";
    const postBody = {
      category_id: url_id,
      offer_type: "",
    };
    const requestOptions = {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(postBody),
    };

    fetch(url, requestOptions)
      .then((response) => response.json())
      .then((json) => {
        this.setState({ data: json });
        // console.log('sasasas')
        // console.log(json)
      })
      .catch((error) => console.error(error))
      .finally(() => {
        this.setState({ isLoading: false });
      });
  }

  render() {
    if (!this.state.data.stores) {
      return null;
    }
    const ListStores = this.state.data.stores;
    return (
      <Fragment>
        <TopMenuStrip />
        <LogoSection />
        <Menu />
        <Grid className="store-list">
          <Grid.Column width={16}>
            <p>
              <span>{this.state.data.heading_label}</span>
            </p>
          </Grid.Column>
        </Grid>
        <Grid columns={4} className="all-offers storeList">
          {ListStores.map((x) => {
            return (
              <Grid.Column>
                <Segment>
                  <Card>
                    <Link to={x.store_url}>
                      {" "}
                      <Image
                        src={x.image}
                        alt=""
                        className="collection-img"
                      ></Image>
                    </Link>
                    <Card.Content>
                      <Link to={x.store_url}>
                        {" "}
                        <Card.Header>{x.name}</Card.Header>
                      </Link>
                      <Card.Description>{x.store_summary}</Card.Description>
                    </Card.Content>
                    <Card.Content extra>
                      <p className="rewards">
                        <span>
                          <img src="/images/rewards.png" alt=""></img>
                        </span>
                        Cash rewards upto <span>AED {x.cashback}</span>
                      </p>
                      <p className="location">
                        <span>
                          <img src="/images/location.png" alt=""></img>
                        </span>

                        {x.store_branches.map((locations, index) => (
                          <span className="store-location">
                            {index === 0 ? (
                              <span>{locations.store_location}</span>
                            ) : index >= 1 ? (
                              <span>
                                ,&nbsp;&nbsp;{locations.store_location}
                              </span>
                            ) : null}
                          </span>
                        ))}
                      </p>
                    </Card.Content>
                  </Card>
                </Segment>
              </Grid.Column>
            );
          })}
        </Grid>
        <Footer />
        <CopyRight />
      </Fragment>
    );
  }
}
export default withRouter(CategoriesList);

【问题讨论】:

  • 您正在渲染三个具有相同路径的路由"/store/:name/:id",因此第一个渲染Store 将由Switch 匹配和渲染。您还在 component 属性上进行渲染并将子节点传递给您的路线,只需在 Route 中选择一种渲染方法。什么和正在渲染Menu 组件?
  • 这是 /store/:name/:id/ 工作正常,不重新加载此类别/:name/:id 请提供一些代码
  • 什么是在链接不工作的地方呈现Menu 组件?
  • 我在这个 上渲染了菜单组件,但页面内容没有改变.
  • Menu 在哪里渲染?那是一个带有Image 组件的链接。链接的to 属性的x.category_url 的值是多少?

标签: reactjs react-router-dom


【解决方案1】:

问题

您要链接的 CategoriesList 组件已安装,因此该组件没有响应或响应 nameid 路由匹配参数更新。

解决方案

我假设您希望/需要在组件更新时也运行在组件挂载上运行的相同逻辑。您可以将此逻辑重构为一个实用函数,以便在 componentDidMount 中调用,就像您已经做的那样,而不是在 componentDidUpdate 中调用。

getData = () => {
  const { id } = this.props.match.params;
  
  const url = "http://localhost:3000/api/v4/web/list";
  const postBody = {
    category_id: id,
    offer_type: "",
  };

  const requestOptions = {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(postBody),
  };

  this.setState({ isLoading: true });

  fetch(url, requestOptions)
    .then((response) => response.json())
    .then((json) => {
      this.setState({ data: json });
    })
    .catch((error) => console.error(error))
    .finally(() => {
      this.setState({ isLoading: false });
    });
}

componentDidMount() {
  this.getData();
}

componentDidUpdate(prevProps) {
  if (prevProps.match.params.id !== this.props.match.params.id) {
    this.getData();
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-13
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 2015-12-22
    • 2020-02-05
    相关资源
    最近更新 更多