简体   繁体   中英

“Unhandled Rejection (TypeError): Cannot read property 'dispatch' of undefined” react-redux error

I was going through a react-redux tuturial. I'm getting this error on my App.js.

"Unhandled Rejection (TypeError): Cannot read property 'dispatch' of undefined"

  19 | class App extends React.Component {
  20 |   componentDidMount() {
  21 |     axios.get('http://localhost:3000/db.json').then(({ data }) => {
> 22 |       window.store.dispatch(setPizzas(data.pizzas));
  23 |     });
  24 |   }
  25 | 

Here's my App.js:

import React from 'react';
import { Route } from 'react-router-dom';
import axios from 'axios';

import { setPizzas } from './redux/actions/pizzas';
import { connect } from 'react-redux';

import { Header } from './components';
import { Home, Cart } from './pages';

class App extends React.Component {
  componentDidMount() {
    axios.get('http://localhost:3000/db.json').then(({ data }) => {
      window.store.dispatch(setPizzas(data.pizzas));
    });
  }

  render() {
    console.log(this.props.items);
    return (
      <div className='wrapper'>
        <Header />
        <div className='content'>
          <Route
            exact
            path='/'
            render={() => <Home items={this.props.items} />}
          />
          <Route exact path='/cart' component={Cart} />
        </div>
      </div>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    items: state.pizzas.items,
  };
};

export default connect(mapStateToProps)(App);

My index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import { Provider } from 'react-redux';

import store from './redux/store';

import './scss/app.scss';

import App from './App';

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

I tried console.log(this.props.items) and got emty array, I think it means my store exist at start, but why cant I dispatch it later?

const mapDispatchToProps = dispatch => {
    return {
        onSetPizzas: (pizzas) => setPizzas(pizzas)
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(App);

and do call it as below

 componentDidMount() {
    axios.get('http://localhost:3000/db.json').then(({ data }) => {
      props.onSetPizzas(data.pizzas);
    });
  }

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