我有一个看起来像这样的组件:
class Table extends Component {
constructor(props) {
super(props);
this.columnDefs = columnDefs;
this.state = {
isLoading: true,
showTimeoutModal: false,
tableData: [],
currentDate: null
};
}
componentDidMount() {
this.fetchData();
}
fetchData() {
this.setState({
isLoading: true,
currentDate: this.props.currentDate
});
someApi.getData(this.props.currentDate).then(tableData => this.setState({
tableData: tableData,
isLoading: false
}))
.catch(error => {
if (error.message === 'timeout') {
this.setState({
showTimeoutModal: true
});
} else {
throw new Error(error.message);
}
});
}
onGridReady(params) {
this.gridApi = params.api;
this.gridApi.sizeColumnsToFit();
}
renderGrid() {
const { tableData, isLoading, showTimeoutModal } = this.state;
let currentView = null;
console.log(this.props.currentDate);
console.log(this.state.currentDate);
if (!isLoading) {
if (tableData) {
currentView =
<div>
<AgGridReact
columnDefs={this.columnDefs}
rowData={tableData}
pagination
paginationPageSize={25}
headerHeight="43"
onGridReady={params => this.onGridReady(params)}
rowSelection="single"
animateRows="true" />
</div>;
} else {
currentView = <h6>There is no job data to display!</h6>;
}
} else if (showTimeoutModal) {
currentView = <div>
<TimeoutModalComponent />
<h6>Timed out</h6>
</div>;
} else {
currentView = <LoadingComponent />;
}
return (
<div>
{currentView}
</div>
);
}
render() {
return (
<div>
{this.renderGrid()}
</div>
);
}
}
export default Table;
它从如下所示的 datepicker 组件获取 currentDate 属性:
class DatePicker extends Component {
constructor(props) {
super(props);
this.onDateChange = this.onDateChange.bind(this);
this.state = {
currentDate: moment(),
focused: false
};
}
onDateChange() {
this.setState({
currentDate: this.props.currentDate
});
}
render() {
return (
<div className="form-group">
<SingleDatePicker
date={this.state.currentDate}
onDateChange={this.onDateChange}
focused={this.state.focused}
onFocusChange={({ focused }) => this.setState({ focused: focused })}
/>
<TableComponent currentDate={`${this.state.currentDate}`} onDateChange={this.onDateChange} />
</div>
);
}
}
export default DatePicker;
当我从日期选择器中选择新日期时,子组件上的 this.props.currentDate 会更新。这是我想要的日期。但是,当该道具更新时,它不会使用新的预期数据重新渲染表格。我意识到我必须更新孩子的状态才能重新渲染表格。我试图通过设置 currentDate: this.props.currentDate 来设置 fetchData() 方法中的状态来做到这一点。但这不起作用,它不会实时更新状态,因此网格不会重新渲染。我想我在概念上遗漏了一些关于反应的东西,但我不确定是什么。我认为 datePicker 组件很好,因为它可以在选择日期时发送正确的日期,并且可以将该日期传递给表格组件。谁能告诉我为什么这个状态不会更新?或者更好的是,
编辑:我现在可以改变状态
componentWillReceiveProps(nextProps, nextContext) {
if (nextProps.currentDate !== this.state.currentDate) {
this.setState({currentDate: nextProps.currentDate});
}
}
但它仍然不会在更新时重新渲染表格。