我是新来的反应者,目前正面临一个问题。
我想进行条件渲染,以便在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;
这将显示驱动程序列表
答案 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
路线`