江戶川亂折騰
2024-01-18 14:34:54
我在 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
提交
取消