我有一系列來自 CMS 的博客,它們呈現出帶有影像/內容等的博客頁面。
然后,在此博客頁面的底部,我建議用戶從陣列中的博客串列中簽出 2 個其他博客。
很簡單,我想從陣列中隨機選擇 2 個博客,但要確保其中一個不是我當前所在的博客頁面,我接近實作這一目標,但使用 for 回圈無法完全正確在 useEffect 中。
我想我可以檢查博客文章的 uid,如果它與當前 url 端點匹配,則使用 state 中的 next & prev 作為陣列的索引跳過它。
這是我的反應檔案:
export default function Case({ data, cases }) {
const [next, setNext] = useState(0);
const [prev, setPrev] = useState(0);
const { results } = cases;
console.log(results);
useEffect(() => {
let currentUrl = window.location.pathname;
currentUrl = currentUrl.split('/')[2];
console.log(currentUrl);
for (let i = 0; i < results.length; i ) {
if (results[i].uid === currentUrl) {
// how to solve here?
}
}
}, []);
return (
<div className='h-full w-full bg-white'>
<div className='bg-gray-100'>
<div className='max-w-5xl mx-auto bg-white py-20 -mt-16 rounded-lg shadow-lg px-8 z-10 relative'>
<div className='flex flex-col md:flex-row justify-around md:space-x-36'>
<div className=''>
<p className='text-3xl text-left'>
{RichText.asText(data.client)}
</p>
<p className='text-xl text-left font-light mt-6'>
{RichText.asText(data.title)}
</p>
</div>
<div className='md:w-1/3 flex flex-col justify-between mt-6 md:mt-0'>
<p className='text-3xl text-blue-500 text-left'>
{RichText.asText(data.overview)}
</p>
<div className='flex space-x-28 items-start mt-8 md:mt-20'>
<div>
<p className='text-xl font-bold'>Category</p>
<p className='mt-8'>{RichText.asText(data.category)}</p>
</div>
<div>
<p className='text-xl font-bold'>Date</p>
<p className='mt-8 whitespace-nowrap'>
{moment(data.date).format('MMM YYYY')}
</p>
</div>
</div>
</div>
</div>
</div>
<div>
<p className='text-3xl text-center'>Want to learn more?</p>
<p className='text-2xl font-light text-center mt-4'>
Check out our other solutions!
</p>
</div>
<div
className='bg-white w-full relative flex justify-center'
style={{ height: '70vh' }}>
<div className='absolute -top-1/3 flex flex-col md:flex-row gap-6'>
<div className='text-center px-8 md:px-0'>
<Link href={`/case-studies/${results[next].uid}`}>
<button className='py-2 px-6 rounded-md bg-blue-500 text-white mt-8'>
{' '}
Read more
</button>
</Link>
</div>
<div className='text-center px-8 md:px-0'>
<Link href={`/case-studies/${results[prev].uid}`}>
<button className='py-2 px-6 rounded-md bg-blue-500 text-white mt-8'>
Read more
</button>
</Link>
</div>
</div>
</div>
</div>
);
}
我敢肯定它很簡單,但任何幫助將不勝感激!
提前致謝。
uj5u.com熱心網友回復:
我不確定uid和currentUrl是否可以正確properties比較,但是您需要過濾results并且最好使用 js es6 陣列方法。
至少邏輯可以幫助你理解。
另外,我不確定您是否需要useEffect.
const { results } = cases;
console.log(results);
let currentUrl = window.location.pathname;
currentUrl = currentUrl.split('/')[2];
console.log(currentUrl);
const filteredResults = results && results.filter(result=>result.uid !== currentUrl)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/404998.html
標籤:
