是否可以在if语句中放置useEffect?
各位,我一直在开发我的登录和仪表板页面。
因此,该页面的工作流程如下所示: 用户进入登录页面,在那里他可以选择插入到表单位置,或按下按钮接收所有位置。现在在后端,我已经创建了两个API,一个用于获取所有位置,另一个用于添加:location
为req.body.param
,然后根据该参数过滤位置。邮递员一切正常。
现在,因为我有两种方法可以让用户获得位置(全部或部分他想要的),所以我想我应该在if语句中放置两个useEffect
,如下所示:
const filter = props.location.data;
if (filter) {
useEffect(() => {
const fetchFiltered = async () => {
const res = await ArticleService.filterByName(filter);
setContent(res.data);
};
fetchFiltered();
}, []);
} else {
useEffect(() => {
const fetchPosts = async () => {
const res = await ArticleService.articles();
setContent(res.data);
};
fetchPosts();
}, []);
}
因此,我的逻辑是,如果有filter
在props.location
内部执行MeuseEffect
,则从获取数据的ArticleService
在API url内发送筛选器。如果没有filter
,只需检索所有数据,并将Content设置为res.data
。
但当我编译代码时,错误是React Hook "useEffect" is called conditionally. React Hooks must be called in the exact same order in every component render
有没有什么方法可以使用我的逻辑来实现这一点,或者我需要创建两个组件:一个是普通仪表板,另一个是用于筛选结果的组件?
用户发送位置的Landing.js
<Form>
<div className='form-group'>
<Input
type='text'
className='form-control text-center'
name='name'
placeholder='Enter desired location'
value={location}
onChange={onChangeLocation}
/>
<Link to={{ pathname: '/dashboard', data: location }}>
<i className='fas fa-check'></i>
</Link>
</div>
<p className='text-center'>or</p>
<Link className='btn btn-primary btn-block' to='/dashboard'>
Show all locations
</Link>
</Form>
Dashboard.js
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import Pagination from 'react-js-pagination';
import ArticleService from '../../services/article.service';
const Dashboard = (props) => {
const [content, setContent] = useState([]);
const [currentPage, setCurrentPage] = useState(1);
const [postsPerPage] = useState(10);
const filter = props.location.data;
if (filter) {
useEffect(() => {
const fetchFiltered = async () => {
const res = await ArticleService.filterByName(filter);
setContent(res.data);
};
fetchFiltered();
}, []);
} else {
useEffect(() => {
const fetchPosts = async () => {
const res = await ArticleService.articles();
setContent(res.data);
};
fetchPosts();
}, []);
}
let counter = content.length;
// Get current posts
const indexOfLastPost = currentPage * postsPerPage;
const indexOfFirstPost = indexOfLastPost - postsPerPage;
const currentPosts = content.slice(indexOfFirstPost, indexOfLastPost);
// Change page
const handlePageChange = (pageNumber) => {
setCurrentPage(pageNumber);
};
const render = (item, index) => {
return (
<tr key={index}>
<td className='text-center'>
<div key={item.id}>
<img
src={`${item.pictures}`}
alt='slika artikla'
className='rounded'
></img>
</div>
</td>
<td className='text-center'>
<div key={item.id}>
<h4>{item.descr}</h4>
<br></br>
<h6 className='text-left'>Number of m2: {item.sqm}m2</h6>
<div className='text-left'>
<small className='text-left'>
{' '}
<a href={item.link} target='_blank' rel='noopener noreferrer'>
Show on website
</a>
</small>
</div>
</div>
</td>
<td className='text-center'>
<div key={item.id}>
<h4>{item.price}</h4>
<small className='text-left'>Price per m2: {item.ppm2}</small>
</div>
</td>
<td className='text-center'>
<div key={item.id}>
<Link to={`/article/${item.id}`}>
<h4>Show</h4>
</Link>
</div>
</td>
</tr>
);
};
return (
<div>
<div className='container'>
<h4 className='text-center'>
Number {counter}
</h4>
<div className='table-responsive'>
<table className='table'>
<thead className='thead-dark'>
<tr>
<th className='text-center' scope='col'>
Pic
</th>
<th className='text-center' scope='col'>
Description
</th>
<th className='text-center w-25' scope='col'>
Price
</th>
<th className='text-center' scope='col'>
Show offer
</th>
</tr>
</thead>
<tbody>{currentPosts.map(render)}</tbody>
</table>
</div>
</div>
<nav>
<div className='w3-bar w3-xlarge'>
<ul className='pagination justify-content-center'>
<li className='page-item'>
<Pagination
hideDisabled
hideNavigation
hideFirstLastPages
currentPage={currentPage}
itemsCountPerPage={10}
totalItemsCount={content.length}
pageRangeDisplayed={indexOfLastPost}
onChange={handlePageChange}
/>
</li>
</ul>
</div>
</nav>
</div>
);
};
export default Dashboard;
谢谢!:d
解决方案
基本答案是,不,您不能有条件地调用useEffect。您必须将条件逻辑放在useEffect回调中。
const filter = props.location.data
useEffect(() => {
if (filter) {
const fetchFiltered = async () => {
const res = await ArticleService.filterByName(filter)
setContent(res.data)
}
fetchFiltered()
} else {
const fetchPosts = async () => {
const res = await ArticleService.articles()
setContent(res.data)
}
fetchPosts()
}
}, [filter, setContent, ArticleService.filterByName, ArticleService.articles])
Reaction中的钩子实际上并不遵循Java脚本的标准规则。它们必须实现的方式有性能方面的原因,通常会进行一些缓存,以防止在每次完成呈现过程时执行多余的代码。
仅在依赖项数组中的一个值(useEffect的第二个参数)发生更改的呈现期间,useEffect挂钩才会运行其回调函数。把所有可能改变的外部价值都放进去是标准的。因此,当Filter的值改变时,应用程序将重新呈现,useEffect将进行比较,意识到有些东西已经改变,并再次运行其回调,然后执行If语句。您可以在performance part of the docs
中阅读有关此内容的更多信息相关文章