为什么列表没有显示在页面上?我的 React-Redux (Api) 应用程序中有哪些错误?以及如何解决它们?



首先,我在React.js上做了一个小应用程序。使用fetch方法,我使用API

这些是我的应用程序的主要文件:

Index.js:(操作(

export const SHOW_AIRPLANES = "SHOW_AIRPLANES";
export function showAirplanes() {
return (dispatch, getState) => {
fetch("https://api.iev.aero/api/flights/25-08-2019").then(response => {
dispatch({ type: SHOW_AIRPLANES, payload: response.data });
});
};
}

aires.js:(减速器(

import { SHOW_AIRPLANES } from '../actions'
const initialState = {
list: []
}
export function showAirplanes(state = initialState, action) {
switch (action.type) {
case SHOW_AIRPLANES:
return Object.assign({}, state, {list: action.payload})
default:
return state 
}
}

index.js(reducer(:

import { combineReducers } from "redux";
import { showAirplanes } from "./airplanes";
const rootReducer = combineReducers({
user: showAirplanes
});
export default rootReducer;

首先,您应该使用createStore函数,如下所示:

const initialData = {}; // whatever you want as initial data
const store = createStore(reducers, initialData, applyMiddleware(thunk));

然后将其传递给您的提供商

<Provider store={store}>
{...}
</Provider

接下来,当您在combineReducers函数中映射reducers时,该对象中的每个键都表示您的一部分状态。所以当你做user: showAirplanes时,这意味着你打算在mapStateToPropsstate.user.list中使用它,所以我认为你打算称它为airplane: showAirplanes

那么,您的减速器名称信息不足,我建议将其更改为airplanesReducer

下一个问题是,对fetch的调用返回一个具有必须解析的JSON的响应。

更改此项:

fetch("https://api.iev.aero/api/flights/25-08-2019").then(response => {
dispatch({ type: SHOW_AIRPLANES, payload: response.data });
});

对此:

fetch("https://api.iev.aero/api/flights/25-08-2019")
.then(res => res.json())
.then(response => {
dispatch({ type: SHOW_AIRPLANES, payload: response.body.departure });
});

请注意,我已经更改了您需要从响应中解析的值。

App.js组件中,您需要创建一个构造函数,并将renderAirplaneList函数绑定到this

// Inside the App class
constructor(props) {
super(props);
this.renderAirplaneList = this.renderAirplaneList.bind(this);
}

最后(我希望我没有遗漏任何其他内容(,将您在App.js组件中的状态映射到{ airplanes: state.airplanes.list},因此您期望在组件中的道具名称为props.airplanes

renderAirplaneList() {
if (!this.props.airplanes.length) {
return null;
}
const arr = this.props.airplanes || [];
return arr.map(airplane => {
return (
<tr key={airplane.id}>
<td>{airplane.ID}</td>
<td>{airplane.term}</td>
<td>{airplane.actual}</td>
<td>{airplane["airportToID.city_en"]}</td>
</tr>
);
});
}

确保你仔细阅读了React和Redux的文档,他们掌握了你需要的所有信息。

祝你好运。

您不打算向这个调用发送一些参数吗?

this.props.showAirplanes()

它似乎有两个参数:状态和操作,尽管状态似乎已经有了它的默认值

最新更新