在我的解决方案中,这是一个包含 React、Redux 和 Kendo React 组件的 ASP.NET Core 项目,我需要将我的 props 作为数组返回。我正在使用 Kendo Dropdown 小部件,如下所示。
<DropDownList data={this.props.vesseltypes} />
但是我收到错误:
Failed prop type: Invalid prop
data
of typeobject
supplied toDropDownList
, expectedarray
.
因此,我检查了从 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
};
Controller /KendoDataController.cs
[HttpGet]
public JsonResult GetVesselTypes()
{
var types = _vesselTypeService.GetVesselTypes();
return Json(types);
}
因此,下拉小部件需要一个数组,我通过商店返回的是一个对象数组。因此,下拉列表不能使用它,因为它不是它所期望的。我的问题是,如何将其作为单个数组或平面数组返回?
最佳答案
首先解构您想要从您的状态映射到属性的部分:
export default connect(
({vesseltypes}) => ({vesseltypes}),
dispatch => bindActionCreators(actionCreators, dispatch)
)(WidgetData);
然后您可以将 VesselTypes 映射到字符串数组,因为这就是 Kendo DropdownList 似乎期望:
<div>
<DropDownList data={this.props.vesseltypes.map((vessel) => vessel.TypeName)} />
</div>
这应该会实现您想要实现的目标。
或者,您可以研究如何实现 HOC 将对象映射到值,它在 Kendo docs 中指定。 ,或者您可以查看 Stackblitz project他们已经准备好了。
关于javascript - 如何在 React with Redux 项目中将 props 数据转换为数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55687976/