简体   繁体   中英

ReactJs :- How to call dispatch on button click

I have below code in Login.js -

import React from 'react'
import {Button} from "reactstrap";
import 'bootstrap/dist/css/bootstrap.min.css';
import { VerifyCredentials } from "./LoginReducers/Login_Action";
import   {GlobalProvider,GlobalConsumer} from "../GlobalStore";
import { LoginReducer } from "./LoginReducers/Login_Reducers";
function Login() {
    return (
        <div>
            <GlobalConsumer>
                {
                    store=>{
                        store.dispatch(LoginReducer)
                    }
                }
            </GlobalConsumer>
            
                <form>
                <input type="text" name="txtLoginId" ></input>
                <input type="password" name="txtPassword" ></input>
                <Button color="success"></Button>
                </form>
            
            
        </div>
    )
}

export default Login

I have Login_Reducer.js-

import Axios from "axios";
import { VerifyCredentials } from "./Login_Action";

const initialState={
    userName:"",
    password:"",
    isVarified:false
}
const url='http://localhost:52016/api/values/';
export const  LoginReducer=(state=initialState,action)=>{
    switch (action.type) {
        case 'VERIFY_CREDENTIALS':
            
            Axios.get(url)
                 .then(x=>{
                     alert(x.data);

                 })
    
        default:
            break;
    }
}

How can I call store.dispatch on button click?

I tried with -

<Button color="success" onClick={() => store.dispatch({ type: 'VERIFY_CREDENTIALS' })}></Button>

But this doesnt helped

Don't write async code inside reducers,

Reducers should return an updated state you are not returning anything from reducers. In default case return existing state.

export const  LoginReducer=(state=initialState,action)=>{
    switch (action.type) {
        case 'VERIFY_CREDENTIALS':
            return {...state, ...action.payload}  
        default:
            return state;
    }
}

Component

async callAPI =() => {
    const url='http://localhost:52016/api/values/'; // move to better place
    const {data} = await Axios.get(url);
    store.dispatch({ type: 'VERIFY_CREDENTIALS', payload: data })
}

<Button color="success" onClick={callAPI}></Button>

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