我有一个使用Redux进行状态管理的React应用。
我希望集成AG-Grid以显示漂亮的数据网格,但是当我尝试将rowData
设置为数据状态时,它不返回任何行。
BookingList.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchBookings } from '../../actions';
import { AgGridReact } from 'ag-grid-react';
import 'ag-grid-community/dist/styles/ag-grid.css';
import 'ag-grid-community/dist/styles/ag-theme-balham.css';
class BookingList extends Component {
componentDidMount() {
this.props.fetchBookings();
}
constructor(props) {
super(props);
this.state = {
columnDefs: [
{
headerName: 'First Name',
field: 'firstName'
},
{
headerName: 'Last Name',
field: 'lastName'
},
{
headerName: 'Email',
field: 'emailAddress'
},
{
headerName: 'Address',
field: 'address'
},
{
headerName: 'Market Date',
field: 'marketDate'
},
{
headerName: 'Stall Type',
field: 'stallType'
}
],
rowData: [this.props.bookings]
};
}
render() {
return (
<div className="ag-theme-balham">
<AgGridReact
columnDefs={this.state.columnDefs}
rowData={this.state.rowData}
/>
</div>
);
}
}
function mapStateToProps({ bookings }) {
return { bookings };
}
export default connect(
mapStateToProps,
{ fetchBookings }
)(BookingList);
如果我使用Material Design Card布局而不是AG-Grid,fetchBookings
确实可以工作并填充数据,所以我现在该零件可以正常工作了。
答案 0 :(得分:2)
您不应在构造函数中使用this
来访问props
:
更改为:
constructor(props) {
super(props);
this.state = {
columnDefs: [
{
headerName: 'First Name',
field: 'firstName'
},
{
headerName: 'Last Name',
field: 'lastName'
},
{
headerName: 'Email',
field: 'emailAddress'
},
{
headerName: 'Address',
field: 'address'
},
{
headerName: 'Market Date',
field: 'marketDate'
},
{
headerName: 'Stall Type',
field: 'stallType'
}
],
rowData: props.bookings // assuming bookings is an array already
};
}
但是,如果您要与redux连接,最好使用props
并使rowData
保持状态不变。
render() {
return (
<div className="ag-theme-balham">
<AgGridReact
columnDefs={this.state.columnDefs}
rowData={this.props.bookings}
/>
</div>
);
}