对组件渲染数据进行两次反应

时间:2019-06-28 17:36:20

标签: javascript reactjs react-router

enter image description here我是新来的反应者,目前正面临一个问题。 我想进行条件渲染,以便在URL包含特定ID的情况下,我渲染其他东西,但是如果满足此条件,则我的组件似乎基本上可以多次进行所有操作。下面是我的代码

import React, { useState, useEffect } from 'react';
import DriverList from './DriverList';
import './Drivers.css';
import getDrivers from '../../Helpers/fetchAny';

function Drivers(props) {
  const url = window.location.href.split('/');
  const last = url.length - 1;
  const urlPattern = /([\d\w]*[-]).*/g;
  const id = url[last];
  const [driverState, setDriverState] = useState({ name: 'Hello' 
});
  const [toDisplayState, setToDisplayState] = useState([]);

  useEffect(() => {
    getDrivers('/api/drivers').then(data => {
      setDriverState(data);
    });
  }, []);

  if (!urlPattern.test(url)) {
    return (
      <div className="mainBody drivers">
        <div className="driver-display" />
        <DriverList />
      </div>
    );
  } else {
    return (
      <div>
        <p>Hello</p>
      </div>
    );
  }
}

export default Drivers;

问题是,如果不满足此条件,它将呈现正常情况下应该重复的内容,通常仅一次(正常)。

组件

import React, { useState, useEffect } from 'react';
import getDrivers from '../../../Helpers/getDrivers';

import { Link } from 'react-router-dom';

function DriverList() {
  const [driverState, setDriverState] = useState([]);
  useEffect(() => {
    getDrivers().then(data => {
      let driverDetails = [];

      for (const driver of data) {
        driverDetails.push({
          driverId: driver.driverID,
          driverName: driver.name,
          driverPhone: driver.phone,
        });
      }
      setDriverState(driverDetails);
    });
  }, []);

  return (
    <div className="driver-list">
      <p className="list-head">Drivers</p>
      {driverState.map((driver, index) => {
        return (
          <Link
            to={`/drivers/${driver.driverId}`}
            className="single-list"
            key={index}
          >
            <span className="list-image" />
            <div>
              <span>
                <i className="mdi mdi-account" /> {driver.driverName}
              </span>
              <span>
                <i className="mdi mdi-phone" /> {driver.driverPhone}
              </span>
            </div>
          </Link>
        );
      })}
    </div>
  );
}

export default DriverList;

这将显示驱动程序列表

1 个答案:

答案 0 :(得分:0)

显然,我在App.js

中重复了该页面的路由
<Route exact path="/" component={Home} />
<Route path="/dashboard" component={Home} />
<Route path="/trips" component={Trips} />
<Route path="/drivers" component={Drivers} />
<Route path="/drivers:driverId” component={Drivers} />

我要做的就是删除routes的onE。

我的理解是react在SPA(单页应用程序)中渲染when you visit a路线`