【发布时间】:2019-04-15 11:14:22
【问题描述】:
在我的解决方案中,它是一个包含 React、Redux 和 Kendo React 组件的 ASP.NET Core 项目,我需要将我的 props 作为数组返回。我正在使用 Kendo Dropdown 小部件,如下所示。
<DropDownList data={this.props.vesseltypes} />
但是我收到以下错误:
道具类型失败:提供给
object类型的无效道具dataDropDownList,预期为array。
所以,我从props.vesseltypes 检查了我返回的数据,这是一个数组而不是平面数组。
这是我如何返回此数据的代码:
components/vessels/WidgetData.js
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { actionCreators } from '../../store/Types';
import { DropDownList } from '@progress/kendo-react-dropdowns';
class WidgetData extends Component {
componentWillMount() {
this.props.requestTypes();
}
render() {
console.log(this.props.vesseltypes)
return (
<div>
<DropDownList data={this.props.vesseltypes} />
</div>
);
}
}
export default connect(
vesseltypes => vesseltypes,
dispatch => bindActionCreators(actionCreators, dispatch)
)(WidgetData);
components/store/Types.js
const requestVesselTypes = 'REQUEST_TYPES';
const receiveVesselTypes = 'RECEIVE_TYPES';
const initialState = {
vesseltypes: [],
isLoading: false
};
export const actionCreators = {
requestTypes: () => async (dispatch) => {
dispatch({ type: requestVesselTypes });
const url = 'api/KendoData/GetVesselTypes';
const response = await fetch(url);
const alltypes = await response.json();
dispatch({ type: receiveVesselTypes, alltypes });
}
}
export const reducer = (state, action) => {
state = state || initialState;
if (action.type === requestVesselTypes) {
return {
...state,
isLoading: true
};
}
if (action.type === receiveVesselTypes) {
alltypes = action.alltypes;
return {
...state,
vesseltypes: action.alltypes,
isLoading: false
}
}
return state;
};
最后,reducer 是在 store 中定义的
components/store/configureStore.js
const reducers = {
vesseltypes: Types.reducer
};
Controllers/KendoDataController.cs
[HttpGet]
public JsonResult GetVesselTypes()
{
var types = _vesselTypeService.GetVesselTypes();
return Json(types);
}
所以,下拉小部件需要一个数组,我通过商店返回的是一个对象数组。因此,下拉菜单不能使用它,因为它不是它所期望的。我的问题是,如何将其作为单个数组或平面数组返回?
【问题讨论】:
-
你确定它不是
this.props.vesseltypes.vesseltypes或者你没有在初始化时传递null吗? -
好吧,我对 Kendo 了解不多,但我可以告诉你,所发生的一切就是你从 Kendo api 获得了一个对象数组,然后商店返回了该对象数组。数组上的这些对象包含各种信息,这意味着您不能简单地将它们转换为数组本身。什么样的信息应该传递给下拉菜单?您要么必须从 Kendo API 发送格式正确的数据,要么必须选择不想显示的信息,然后自己将对象数组转换为平面数组,最好在 reducer 中。
标签: javascript reactjs asp.net-core redux react-redux