我只是尝试在react redux中制作简单的reducer,但从未调用过。经过大量试用后,我不知道为什么它不起作用。正在显示console.log,但从未调用过reducer。
import React from "react";
import { connect } from "react-redux";
import * as actions from "store/actions";
function Login(props) {
const login = (e) => {
e.preventDefault();
props.login();
};
return (
<form onSubmit={login}>
<button> login </button>
</form>
);
}
const mapDispatchToProps = (dispatch) => {
return {
login: () => dispatch(actions.login),
};
};
export default connect(null, mapDispatchToProps)(Login);
动作文件-我在这里console.log显示正确
import * as actionsTypes from "./actionTypes";
export const logout = () => {
return {
type: actionsTypes.AUTH_LOGOUT,
};
};
export const login = () => {
console.log("i'm here")
return {
type: actionsTypes.AUTH_LOGIN,
};
};
减速器
import * as actionTypes from "../actions/actionTypes";
const initialState = {
isLogged: false,
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case actionTypes.AUTH_LOGIN:
return {
...state,
isLogged: true,
};
case actionTypes.AUTH_LOGOUT:
return {
...state,
isLogged: false,
};
default:
return state;
}
};
export default reducer;
非常感谢您的帮助
答案 0 :(得分:1)
可能您忘记配置商店本身了吗? :)
类似的东西:
// at configureStore.js
import { createStore } from 'redux';
import reducer from '../path/to/your/root/reducer'; // assuming that you use combineReducer function to gather all reducers in one place
export default createStore(reducer);
然后在您的应用程序根目录中,需要使用商店提供商包装输入组件:
import store from './store/configureStore';
import { Provider } from 'react-redux';
export default () => (
<Provider store={store}>
<AppRootComponent />
</Provider>
);
AppRootComponent
->您的初始应用程序组件
UPD :
似乎您是在尝试将动作创建者传递给dispatch
函数,而不是实际调用它。只需在dispatch
中呼叫该创建者:
login: () => dispatch(actions.login()),
顺便说一句,这是您案子的working example