仅在状态更改时使用useEffect

时间:2020-04-27 06:56:59

标签: reactjs redux react-hooks use-effect

我有useEffect,它从action调用redux来获取上传内容

useEffect(() => {
    getUploads()
}, [getUploads])

但是,我只想在状态更改时获取,而不是每次组件渲染时都获取。 我已经将状态映射为:

{filteredUploads.map((image, i) => { return (...) })}

我尝试添加getUploadsfilteredUploadsfilteredUploads.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()))
    };
}

1 个答案:

答案 0 :(得分:1)

要在状态更新时调用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
}