简体   繁体   中英

Aplication works but generates an error: mapDispatchToProps() in Connect(App) must return a plain object. Instead received undefined

I have written small app with Redux/Thunk. It works but it also generates an error msg as in title. By work and not work here I mean receiving content from external file and make it available to app

I have tried to rewrite critical fragment to syntax probably more correct, but then it stopped working. By work and not work here I mean receiving content from external file and make it available to application. The very general idea is that when App.js (React/Hooks) is mounted it dispatches Thunk action of getting data from external source.

Here is shortened version of index.js

import thunk from 'redux-thunk';
import { Provider } from 'react-redux';
import {reducer} from './reducer';

const store = createStore(reducer, applyMiddleware(thunk) );


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

Here below part of actions.js


export function getData() {

  return dispatch => {

    // set state to "loading"
    dispatch(getDataRequested());

    fetch("https://api.myjson.com/bins/8qjek")
      .then(response => response.json())
      .then(data => {
        // set state for success
        const dane = data.map(Object.values);
        dispatch(getDataDone(dane));

      })
      .catch(error => {
        // set state for error
        dispatch(getDataFailed(error));
      })
  }
}

and of App.js


  useEffect(() => getData(), []);
  const {state} ={...props}



const mapStateToProps = (state) => {
  return {state};
};

const mapDispatchToProps = getData;

const ConnectedApp = connect(mapStateToProps, mapDispatchToProps)(App);

export default ConnectedApp;

I have checked two other versions of mapDispatchToProps, but while probably syntactically correct, I do not receive content.

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

and

const mapDispatchToProps = {getData: getData()}

Could someone help me? That is shortened version, I can of course add any code necessary.

You have to use bindActionCreators from the redux library.

Like so:

import { bindActionCreators } from 'redux';

const mapDispatchToProps = dispatch =>
  bindActionCreators(ActionCreators, dispatch);

Where ActionCreators could be your getData .

Try adding dispatch call before calling action creator getData() .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM