首页 文章

Redux动作不会触发减速器

提问于
浏览
2

问题

我将我的反应应用程序连接到Redux商店,添加了一个api操作来从我的后端收集数据,包括中间件redux-promise . 大多数事情似乎都有效,因为我可以在React网页编辑器中看到我的商店以及联合收割机减速键 . 当我调用我的动作时,它会起作用并且控制台记录完成的保证 . 但是,我的减速器从未运行过 . 我认为这是我在主容器上发送的一个问题,但是我已经尝试过各种我能想到的方式 - regular dispatch()和bindActionCreators . 救命!

Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.js';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import promiseMiddleware from 'redux-promise';
import RootReducer from './reducers';

const createStoreWithMiddleware = applyMiddleware(promiseMiddleware)(createStore)

let store = createStore(RootReducer);

ReactDOM.render(
            <Provider store={store}>
                <App />
            </Provider>, 
            document.getElementById('root'));`

结合减速器

import { combineReducers } from 'redux';
import ReducerGetPostings from './reducer_get_postings'

const rootReducer = combineReducers({
    postingRecords: ReducerGetPostings
})

export default rootReducer;

减速机

import { FETCH_POSTINGS } from '../actions/get_postings'

export default function (state = null, action) {
    console.log('action received', action)
    switch (action.type) {
        case FETCH_POSTINGS:
            return [ action.payload ]
    }
    return state;
}

动作API

import axios from 'axios';
import { url } from '../api_route';

export const FETCH_POSTINGS = 'FETCH_POSTINGS'

export function fetchpostings() {
    const postingRecords = axios.get(`${url}/api/postings`)

    console.log('Postings', postingRecords)
    return {
        type: FETCH_POSTINGS,
        payload: postingRecords
    };
}

容器

import { connect } from 'react-redux';
import { bindActionCreators } from 'redux'
import { fetchpostings } from '../../actions/get_postings.js'

class Dashboard extends Component {

    //....lots of other functionality already built here.

    componentDidMount() {
      axios.get(`${url}/api/postings`)
        .then(res => res.data)
        .then(
          (postingRecords) => {
            this.setState({
              postingData: postingRecords,
              postingOptions: postingRecords
            });
          },
          (error) => {
            this.setState({
              error
            })
          }
        )
    // primary purpose is to replace the existing api call above with Redux Store and fetchpostings action creator

        fetchpostings()
    }
}

function mapDispatchToProps(dispatch) {
   // return {actions: bindActionCreators({ fetchpostings }, dispatch)}
  return {
    fetchpostings: () => dispatch(fetchpostings())
  }
}

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

1 回答

  • 3

    当您在componentDidMount中调用 fetchpostings() 时,您正在调用从 actions/get_postings.js 导入的方法,而不是将要调度的方法,则不会调度您的操作 .

    请尝试 this.props.fetchpostings() .

    你也没有将状态绑定到你需要做的道具上 .

相关问题