【问题标题】:Dispatched actions reach the action creator but not the receiver分派的动作到达动作创建者而不是接收者
【发布时间】:2021-05-30 07:25:18
【问题描述】:

我的toolbar 组件调度了一个动作abortGame()。我在控制台中看到它到达了动作创建者(文本“ONE!”显示在控制台上),但从未到达减速器(文本“TWO!”从未显示)。

怎么了?

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import App from './App';
import reducer from './store/reducers/reducer';

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(reducer, composeEnhancers(
  applyMiddleware(thunk)
));

const app = (
  <React.StrictMode>
    <Provider store={store}>
      <BrowserRouter>
        <App />
      </BrowserRouter>
    </Provider>
  </React.StrictMode>
);

ReactDOM.render(app, document.getElementById('root'));

reducer.js

import * as actionTypes from '../actions/actionTypes';

const initialState = {
    score: 0
};

const reducer = (state = initialState, action) => {

    switch (action.type) {

        case actionTypes.ABORT_GAME:
            console.log('TWO');
            return {
                ...state,
                score: 0,
            };

        default:
            return state;
    }
};

export default reducer;

actionTypes.js

export const ABORT_GAME = 'ABORT_GAME';

actions.js

import * as actionTypes from './actionTypes';

export const abortGame = () => {
    console.log('ONE!');
    return {
        type: actionTypes.ABORT_GAME
    };
};

Toolbar.js(组件)

import React from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { abortGame } from '../../store/actions/actions';
    
const toolbar = (props) => (
        <div>
            <div onClick={props.onAbortGame}><Link to="/">MyApp</Link></div>
        </div>
);

const mapDispatchToProps = dispatch => {
    return {
        onAbortGame: () => dispatch(abortGame)
    };
};

export default connect(null, mapDispatchToProps)(toolbar);

【问题讨论】:

    标签: javascript reactjs redux


    【解决方案1】:

    您在调度操作时错过了函数括号

    const mapDispatchToProps = dispatch => {
        return {
            onAbortGame: () => dispatch(abortGame)
        };
    };
    

    只需将这一行 onAbortGame: () =&gt; dispatch(abortGame) 更改为 onAbortGame: () =&gt; dispatch(abortGame())

    abortGame 是一个动作创建器,它基本上是一个函数。所以你需要在 dispatch 里面调用函数

    【讨论】:

      【解决方案2】:

      你只是在 dispatch 中传递了函数名,而不是准确地调用它。 只需转换 dispatch(abortGame())

      sandbox working link

      【讨论】:

        猜你喜欢
        • 2017-12-12
        • 2017-02-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多