【问题标题】:ReactJs :- How to call dispatch on button clickReactJs :- 如何在按钮单击时调用调度
【发布时间】:2020-12-23 15:41:07
【问题描述】:

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

但这并没有帮助

【问题讨论】:

标签: javascript reactjs redux


【解决方案1】:

不要在 reducer 中编写异步代码,

Reducers 应该返回一个更新的状态,你没有从 reducer 返回任何东西。默认情况下返回现有状态。

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

组件

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-11
    • 2019-08-09
    • 2021-04-06
    • 1970-01-01
    • 2017-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多