В чем может быть проблема с этим приложением Redux (реагировать)? - PullRequest
0 голосов
/ 07 февраля 2020

У меня проблемы с кодом, но я не могу понять, в чем дело.

Я пытаюсь создать проект для одного компонента приложения, чтобы лучше понять, но я я не могу получить состояние heroes.

Я бы хотел лучше понять Redux, и после этого проекта я разделю файлы, но мне было проще использовать одно приложение для начала.

Мой код

import React from 'react';
import './App.css';
import { createStore, applyMiddleware, compose, combineReducers } from 'redux';
import { Provider, connect } from 'react-redux';
import thunk from 'redux-thunk';
import PropTypes from 'prop-types';

const initialState = {
  heroes: [
    {id: 1, name: 'Superman'},
    {id: 2, name: 'Batman'},
    {id: 3, name: 'Robin'},
    {id: 4, name: 'Spiderman'},
    {id: 5, name: 'Thor'}
  ]
}
const GET_HEROES = 'GET_HEROES';

const getHeroes = () => {
  return {
    type: GET_HEROES,
    text: 'Getting all the heroes'
  }
}

const heroReducer = function(state = initialState, action) {
  switch(action.type) {
    case GET_HEROES:
      console.log(state);
      return { ...state }
    default:
      console.log(state);
      return state
  }
}
const rootReducer = combineReducers ({
  hero: heroReducer
});

const store = createStore(rootReducer, initialState, applyMiddleware(thunk));

class App extends React.Component {



  componentDidMount() {
    getHeroes();
  }

  render() {
    return (
      <Provider store={store}>
        <h1>Hello world</h1>
        <ul>
          {[1,2,3].map(item => (
            <li>{item}</li>
          ))}
        </ul>
      </Provider>
    );
  };
}

App.propTypes = {
  getHeroes: PropTypes.func.isRequired,
  hero: PropTypes.object.isRequired
}

export default (App);

Ответы [ 2 ]

1 голос
/ 07 февраля 2020

Приложение не может получить состояние героев, потому что оно не подключается к редуксу. Вы можете использовать функцию «подключения», чтобы установить связь между приложением и промежуточным программным обеспечением Redux. Вам также необходимо добавить mapStatetoProps () и mapDispatchtoProps () в функции соединения.

  • mapStatetoProps (), чтобы связать компонент приложения с redux.
  • mapDispatchProps (), в порядке для отправки действия redux на компонент приложения.

Код должен быть таким:

index.js

import React from 'react';
import App from './App.js';
import { createStore, applyMiddleware, compose, combineReducers } from 'redux';
import { Provider, connect } from 'react-redux';
import thunk from 'redux-thunk';
import PropTypes from 'prop-types';

const initialState = {
  heroes: [
    {id: 1, name: 'Superman'},
    {id: 2, name: 'Batman'},
    {id: 3, name: 'Robin'},
    {id: 4, name: 'Spiderman'},
    {id: 5, name: 'Thor'}
  ]
}
const GET_HEROES = 'GET_HEROES';

const getHeroes = () => {
  return {
    type: GET_HEROES,
    text: 'Getting all the heroes'
  }
}

const heroReducer = function(state = initialState, action) {
  switch(action.type) {
    case GET_HEROES:
      console.log(state);
      return { ...state }
    default:
      console.log(state);
      return state
  }
}
const rootReducer = combineReducers ({
  hero: heroReducer
});

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

const app = (
  <Provider store={store}>
      <App />
  </Provider>
);

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

app.js

import React from 'react';
import './App.css';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';

class App extends React.Component {
  componentDidMount() {
    this.props.ongetHeroes();
  }

  render() {
    return (
      <h1>Hello world</h1>
        <ul>
        {[1,2,3].map(item => (
          <li>{item}</li>
        ))}
      </ul>
    );
  };
}

App.propTypes = {
  getHeroes: PropTypes.func.isRequired,
  hero: PropTypes.object.isRequired
}

const mapStateToProps = (state) => {
  return {
    heroes: state.hero.heroes
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    ongetHeroes : () => dispatch(getHeroes()),
  };
};

export default connect(mapStatetoProps, mapDispatchtoProps)(App);
0 голосов
/ 07 февраля 2020

Посмотрите на connect ...

Пример использования вашего кода:

const mapDispatchToProps = {
    getHeros: getHeros
};

const mapStateToProps = state => {
    return {
        heros: state.heros
    }
}

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

...