ReactJs:- 如何在按钮单击时调用调度

我在 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

我有 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;

    }

}

如何在单击按钮时调用 store.dispatch?


我尝试过 -


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

但这没有帮助


江户川乱折腾
浏览 77回答 1
1回答

暮色呼如

不要在减速器中编写异步代码,减速器应该返回更新的状态,您没有从减速器返回任何内容。默认情况下返回现有状态。export const&nbsp; LoginReducer=(state=initialState,action)=>{&nbsp; &nbsp; switch (action.type) {&nbsp; &nbsp; &nbsp; &nbsp; case 'VERIFY_CREDENTIALS':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return {...state, ...action.payload}&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return state;&nbsp; &nbsp; }}成分async callAPI =() => {&nbsp; &nbsp; const url='http://localhost:52016/api/values/'; // move to better place&nbsp; &nbsp; const {data} = await Axios.get(url);&nbsp; &nbsp; store.dispatch({ type: 'VERIFY_CREDENTIALS', payload: data })}<Button color="success" onClick={callAPI}></Button>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript