打字稿React-Redux-动作未达到减速器

时间:2020-05-22 03:30:51

标签: reactjs typescript redux react-redux

我是Redux的新手。我正在尝试在我的React应用程序中实现Redux,但是由于某种原因,这些操作未达到我的简化器。我正在关注以下示例:https://codesandbox.io/s/9on71rvnyohttps://codesandbox.io/s/w02m7jm3q7

由于某种原因,我无法使其正常运行。这是我的代码:

Redux:

store / index.ts

import { createStore, combineReducers } from "redux";
import { composeWithDevTools } from "redux-devtools-extension";

import { sidebarReducer } from "./sidebar/reducers";

const rootReducer = combineReducers({
    sidebar: sidebarReducer
});

export type AppState = ReturnType<typeof rootReducer>;

export default function configureStore() {
    const store = createStore(rootReducer, composeWithDevTools());
    return store;
}

store / sidebar / actions.ts

import { sidebarState, TOGGLE_SIDEBAR } from "./types";

export function toggleSidebar() {
    console.log("hoi");
    return {
        type: TOGGLE_SIDEBAR,
        payload: {}
    }
}

商店/侧边栏/reducers.ts

import { TOGGLE_SIDEBAR, sidebarState, SidebarActionTypes } from "./types";

const initialState: sidebarState = {
    isOpen: false
}

export function sidebarReducer(state = initialState, action: SidebarActionTypes): sidebarState {
    switch (action.type) {
        case TOGGLE_SIDEBAR: {
            console.log("Haai");
            return {
                ...state,
                isOpen: !state.isOpen
            };
        }
        default:
            return state;
    }
}

商店/侧边栏/types.ts

export interface sidebarState {
    isOpen: boolean;
}

export const TOGGLE_SIDEBAR = "TOGGLE_SIDEBAR";

interface ToggleSidebarAction {
    type: typeof TOGGLE_SIDEBAR;
    payload: sidebarState;
}

export type SidebarActionTypes = ToggleSidebarAction;

反应:

components / navbar / navbar.tsx

import React from 'react';
import './navbar.scss';
import '../../css/spacing.scss';
import { toggleSidebar } from '../../store/sidebar/actions'
import { connect } from "react-redux";

class Navbar extends React.Component {

    constructor(props: any) {
        super(props);
    }

    render() {

        return (
                <li className="nav-link sidebar-link" onClick={() => toggleSidebar()}>
                    <i className="fas fa-bars fa-lg fa-fw"></i>
                </li>
        )
    }
}

export default connect(null, toggleSidebar)(Navbar);

由于某种原因,这不起作用。当我单击按钮时,它确实到达了动作,但没有到达减速器。我知道我没有调度,但是在我遵循的示例中也没有调度。这两个示例均来自文档,因此应该是正确的。我尝试了很多事情,但没有任何效果。

1 个答案:

答案 0 :(得分:1)

编辑您的connect函数以在第二个参数中接收带有动作函数的对象:

export default connect(null, { toggleSidebar })(Navbar);

现在,connect将执行您的动作简化器并将其传递给dispatch(负责调用简化器),从而创建一个新函数。您可以通过props使用相同的命名在组件上访问此新功能:

<li className="nav-link sidebar-link" onClick={ this.props.toggleSidebar }>