首页 > 解决方案 > 仅当状态改变时才使用效果

问题描述

我有useEffect哪个调用actionfromredux来获取上传

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

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

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

我试图添加getUploads,作为依赖数组filteredUploadsfilteredUploads.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()))
    };
}

标签: reactjsreduxreact-hooksuse-effect

解决方案


要在状态更新时调用钩子,只需在(传递给的第二个参数)useEffect的依赖数组中包含相关的状态变量。useEffectuseEffect

解决useEffect在组件的每个渲染上都被调用的问题:这是因为getUploads在每次渲染上都重新定义了。要解决此问题,您可以使用useDispatchredux 挂钩。这是代替(并假设您当前正在使用)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
}

推荐阅读