简体   繁体   中英

Function gets not executed in Hook

I have a component where I want to dispatch a Redux action through a function. What I do not understand is, the function is not executed. A console.log() right before and after the functioncall bar() gets logged, but when I try to console.log() from the function bar() , that has no effect what so ever... Why is that?

// Foo.js
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import React from 'react';
import { bar } from './actions';

const Foo = () => {
    useEffect(() => {
    console.log('I get logged');
        bar();
    console.log('I get logged too');
    }, [])

    return <Whatever> ... </Whatever>
};


const mapDispatchToProps = dispatch => {
    return bindActionCreators({
        bar,
    }, dispatch)
};

const mapStateToProps = state => {
    const { ... } = state
    return {
        ...: ...
    }
};

export default connect(mapStateToProps, mapDispatchToProps)(Foo);




// actions.js
export const bar = () => async dispatch => {
    console.log('I do not get logged');
    await ... 
    dispatch({ type: ..., ... });
};

Because bar at this point references your unbound action creator, not the one from connect . You would have to use props.bar to get that. But you should not.

Generally, you should not use connect with function components, but the useDispatch and useSelector react-redux hooks instead .

So it should look like

const Foo = () => {
    const dispatch = useDispatch();
    useEffect(() => {
    console.log('I get logged');
        dispatch(bar());
    console.log('I get logged too');
    }, [dispatch])

    return <Whatever> ... </Whatever>
};

without any use of connect anywhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM