Các cách sử dụng dispatch action (2 cách) (ok)

Cách 1:

C:\Users\Administrator\Desktop\pro\src\actions\login.tsx

import * as logins from './../constants/login';
export const loginRequested = ():any => ({
	type: logins.LOGIN_REQUESTED
})
export const loginSuccess = (payload:any) => ({
	type: logins.LOGIN_SUCCESS,
	payload
})
export const loginFailed = (payload:any) => ({
	type: logins.LOGIN_FAILED,
	payload
})

C:\Users\Administrator\Desktop\pro\src\middlewares\thunks.tsx

import { Dispatch } from 'redux';
import * as actions from './../actions/login';
export const login = (payload: any) => (dispatch:any) => {
	dispatch(actions.loginRequested());
}

C:\Users\Administrator\Desktop\pro\src\pages\Login\index.tsx

import React, {useState } from 'react';
import { connect } from 'react-redux';
import {login} from './../../middlewares/thunks';
const Login = (props:any) => {
}
....................
const mapStateToProps = (state: any) => ({
	authenticated: state.app.isAuthenticated
})
const dispatchToProps = {
	login
}
export default connect(mapStateToProps, dispatchToProps)(Login);

Cách 2:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import Products from './../components/Products';
import Product from './../components/Product';
import PropTypes from 'prop-types';
import {actAddToCart, actChangeMessage} from './../actions/index';
class ProductsContainer extends Component {
}
.................................
var mapDispatchToProps = (dispatch, props) => {
    return {
        onAddToCart : (product) => {
            dispatch(actAddToCart(product,1))
        },
        onChangeMessage: (message) => {
            dispatch(actChangeMessage(message));
        }
    }
};
export default connect(mapStateToProps, mapDispatchToProps)(ProductsContainer);

Last updated

Was this helpful?