Redux newb ie здесь.
Я изучаю курс Udemy по Redux и создаю приложение robofriends, которое получает данные из API и возвращает их обратно в мое приложение.
Я прошел курс, но в самом конце ошибок нет, но контент не загружается. Он просто зависает при загрузке.
В консоли разработчика я вижу в Redux, что приложение успешно извлекло данные из API, но оно просто не отобразит их.
Здесь это рассматриваемый код:
**
**
import {
CHANGE_SEARCH_FIELD,
REQUEST_ROBOTS_PENDING,
REQUEST_ROBOTS_SUCCESS,
REQUEST_ROBOTS_FAILED
} from "./constants";
export const setSearchField = text => ({
type: CHANGE_SEARCH_FIELD,
payload: text
});
export const requestRobots = () => dispatch => {
dispatch({ type: REQUEST_ROBOTS_PENDING });
fetch("https://jsonplaceholder.typicode.com/users")
.then(data => dispatch({ type: REQUEST_ROBOTS_SUCCESS, payload: data }))
.catch(error => dispatch({ type: REQUEST_ROBOTS_FAILED, payload: error }));
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
**
**
import {
CHANGE_SEARCH_FIELD,
REQUEST_ROBOTS_PENDING,
REQUEST_ROBOTS_SUCCESS,
REQUEST_ROBOTS_FAILED
} from "./constants.js";
//INITIAL STATE
const initialStateSearch = {
searchField: ""
};
//SEARCHROBOTS PURE FUNCTION (React docs recommends switch statements)
export const searchRobots = (state = initialStateSearch, action = {}) => {
switch (action.type) {
case CHANGE_SEARCH_FIELD:
//Returning a new state and assign action.payload to the new searchField
return Object.assign({}, state, { searchField: action.payload });
default:
return state;
}
};
const initialStateRobots = {
isPending: false,
robots: [],
error: ""
};
export const requestRobots = (state = initialStateRobots, action = {}) => {
switch (action.type) {
case REQUEST_ROBOTS_PENDING:
return Object.assign({}, state, { isPending: true });
case REQUEST_ROBOTS_SUCCESS:
return Object.assign({}, state, {
robot: action.payload,
isPending: false
});
case REQUEST_ROBOTS_FAILED:
return Object.assign({}, state, {
error: action.payload,
isPending: false
});
default:
return state;
}
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
**
**
import React, { Component } from "react";
import { connect } from "react-redux";
import Cardlist from "../components/Cardlist";
import SearchBox from "../components/SearchBox";
import "./App.css";
import Scroll from "../components/Scroll";
import { ButtonToolbar } from "react-bootstrap";
import { setSearchField, requestRobots } from "../actions.js";
//State to listen for
const mapStateToProps = state => {
return {
searchField: state.searchRobots.searchField,
robots: state.requestRobots.robots,
isPending: state.requestRobots.isPending,
error: state.requestRobots.error
};
};
//State to listen for and dispatch
const mapDispatchToProps = dispatch => {
return {
onSearchChange: event => dispatch(setSearchField(event.target.value)),
onRequestRobots: () => dispatch(requestRobots())
};
};
class App extends Component {
componentDidMount() {
this.props.onRequestRobots();
}
render() {
const { searchField, onSearchChange, robots, isPending } = this.props;
const filteredRobots = robots.filter(robot => {
return robot.name.toLowerCase().includes(searchField.toLowerCase());
});
return !isPending ? (
<h1>Loading</h1>
) : (
<div className="tc">
<h1 className="f1">Robofriends</h1>
<SearchBox searchChange={onSearchChange} />
<Scroll>
<Cardlist robots={filteredRobots} />
</Scroll>
</div>
);
}
}
//'Connect' connects this app container to the redux state
export default connect(mapStateToProps, mapDispatchToProps)(App);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
import React from "react";
import ReactDOM from "react-dom";
import { Provider, connect } from "react-redux";
import { createStore, applyMiddleware, combineReducers } from "redux";
import { createLogger } from "redux-logger";
import thunkMiddleware from "redux-thunk";
import "./index.css";
import App from "./containers/App.js";
import * as serviceWorker from "./serviceWorker";
import { searchRobots, requestRobots } from "./reducers";
import "tachyons";
import "bootstrap/dist/css/bootstrap.min.css";
const logger = createLogger();
const rootReducer = combineReducers({ searchRobots, requestRobots });
const store = createStore(
rootReducer,
applyMiddleware(thunkMiddleware, logger)
);
ReactDOM.render(
//Provides store to all components
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);
serviceWorker.unregister();
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
**
**
Итак, он должен отображать это:
Как это должно работать
Но вместо этого это просто застрял на этом:
Не могу пройти загрузку
Может кто-нибудь помочь мне с этим? Надеюсь, все понятно!
Спасибо