Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a dispatch (react-redux) into class Component

My code

class LoginPage extends Component {

  render() {
    return (
        <div>
          <TextInput/>
          <br/>
          <TextInput/>
          <br/>
          <Button onClick={() => {
            const dispatcher = useDispatch();
            dispatcher(singIn())
          }}>SING IN</Button>
        </div>
    );
  }
}

enter image description here

I guess that I am using a hooks in a class component, but what can I use instead of useDispacth to my LoginPage?

like image 397
Mauricio Loya Avatar asked Apr 08 '20 04:04

Mauricio Loya


People also ask

Can Redux be used with class components?

Redux is a library that allows a React app to create a global state object that can be used in any component across the app by consuming the state object.

How do I dispatch an action in React Redux?

dispatch is a function of the Redux store. You call store.dispatch to dispatch an action. This is the only way to trigger a state change. With React Redux, your components never access the store directly - connect does it for you. React Redux gives you two ways to let components dispatch actions:

What is the use of Dispatch in Redux?

dispatch is a function of the Redux store. You call store.dispatch to dispatch an action. This is the only way to trigger a state change. With React Redux, your components never access the store directly - connect does it for you. React Redux gives you two ways to let components dispatch actions:

What is the difference between react connect and React Redux?

With React Redux, your components never access the store directly - connect does it for you. React Redux gives you two ways to let components dispatch actions: By default, a connected component receives props.dispatch and can dispatch actions itself.

How do I trigger a state change in React Redux?

dispatch is a function of the Redux store. You call store.dispatch to dispatch an action. This is the only way to trigger a state change. With React Redux, your components never access the store directly - connect does it for you.


1 Answers

For class components, you need to use connect method from react-redux. Use connect method and pass mapDispatchToProps function as shown below.

import { connect } from 'react-redux';
class LoginPage extends Component {

    render() {
        return (
            <div>
                <TextInput/>
                <br/>
                <TextInput/>
                <br/>
                <Button onClick={() => {
                    this.props.singIn()
                }}>SING IN</Button>
            </div>
        );
    }
}



const mapDispatchToProps = (dispatch) => {
    return {
        signIn: () => dispatch(signIn())
    }
};
export default connect(null, mapDispatchToProps)(LoginPage)

Read thru the doc for more info. https://react-redux.js.org/api/connect

like image 58
gdh Avatar answered Oct 16 '22 21:10

gdh