reactjs - 仅当状态改变时才使用效果
问题描述
我有useEffect
哪个调用action
fromredux
来获取上传
useEffect(() => {
getUploads()
}, [getUploads])
但是,我只想在状态更改时获取,而不是在每次组件呈现时获取。我已经将状态映射为:
{filteredUploads.map((image, i) => { return (...) })}
我试图添加getUploads
,作为依赖数组filteredUploads
。filteredUploads.length
都没有奏效。
我的redux-action
:
export const getUploads = () => async dispatch => {
try {
dispatch({ type: 'LOADING', payload: true })
const res = await axios.get('/uploads/myuploads')
dispatch({
type: GETMYUPLOAD_SUCCESS,
payload: res.data
})
} catch (err) {
const error = err.response.data.error[0].msg
dispatch(setAlert(error, 'danger'))
}
}
mapStatetoProps
:
function mapStateToProps(state) {
const { myuploads, searchField } = state.useruploads;
return {
searchField: state.useruploads.searchField,
filteredUploads: myuploads.filter((upload) => upload.caption.toLowerCase().includes(searchField.toLowerCase()))
};
}
解决方案
要在状态更新时调用钩子,只需在(传递给的第二个参数)useEffect
的依赖数组中包含相关的状态变量。useEffect
useEffect
解决useEffect
在组件的每个渲染上都被调用的问题:这是因为getUploads
在每次渲染上都重新定义了。要解决此问题,您可以使用useDispatch
redux 挂钩。这是代替(并假设您当前正在使用)mapDispatchToProps
。
这是一个完整的例子:
import { useDispatch } from 'react-redux'
import { getUploads } from "./redux-actions";
const MyComponent = props => {
const dispatch = useDispatch();
const [state, setState] = React.useState({});
useEffect(() => {
dispatch(getUploads());
}, [dispatch, state]);
// rest of component
}
推荐阅读
- c# - 什么是只执行一次的“foreach”循环的最佳替代品?
- javascript - Lambda 下载和转发 PDF(PDF 代理)
- python - 无法用所有列中的列值填充缺失值
- php - 使用 PHP cURL GET 在 Netsuite 中使用 HMAC-SHA256 进行 Oauth
- shopware - 同时更新所有语言的 customField
- php - 通过引用 img src 检索替代文本 - Wordpress
- ios - UICollectionView 开始滚动后更改单元格大小
- amazon-web-services - AWS IAM 策略中要求的资源类型意味着什么
- sql - 来自字符串的 SQL 日期格式
- conditional-statements - Puppet - 如何设置条件来检查是否安装了软件包,如果未安装,我需要跳过它?