我在 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>但这没有帮助
1 回答
暮色呼如
TA贡献1853条经验 获得超9个赞
不要在减速器中编写异步代码,
减速器应该返回更新的状态,您没有从减速器返回任何内容。默认情况下返回现有状态。
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>
添加回答
举报
0/150
提交
取消