从 React 道具中获取数据

如何从中获取数据props并确保数据正确到达。我的问题是,在我的类组件中,我收到警报props,然后我想用警报呈现表格,道具设置异步,我想确保数据到达并且我将能够设置状态。下面是我不太好的尝试解决它,但不起作用(都console.log显示空数组):


  componentDidMount() {

    this.setState({

      startDate: moment()

        .subtract(30, 'days')

        .startOf('day'),

      endDate: moment().endOf('day'),

      selectedSeverity: null,

      isChecked: true,

    });


    if(this.state.tableAlerts.length === 0){

      console.log('tableAlerts', this.state.tableAlerts)

      console.log('householdAlerts', this.props.householdAlerts)

      this.setState({ tableAlerts: this.props.householdAlerts })

    }

  }


波斯汪
浏览 93回答 2
2回答

慕容708150

在构造函数中将初始值设置为状态是不好的做法,因此使用 lifeCycles 作为 componentDidMount 或 componentDidUpdate 来操作状态。&nbsp;export class HouseholdAlertsPure extends React.Component {&nbsp;constructor(props) {&nbsp; super(props);&nbsp; // initial values for state&nbsp; this.state = {&nbsp; tableAlerts: [],&nbsp; startDate: null,&nbsp; endDate: null,&nbsp; selectedSeverity: null,&nbsp; isChecked: false&nbsp; &nbsp; &nbsp;&nbsp;&nbsp;}}componentDidMount() {&nbsp;// values declared for state at component first load&nbsp;this.setState({&nbsp; startDate: moment()&nbsp; &nbsp; .subtract(30, 'days')&nbsp; &nbsp; .startOf('day'),&nbsp; endDate: moment().endOf('day'),&nbsp; selectedSeverity: null,&nbsp; isChecked: true,&nbsp; tableAlerts: this.props.householdAlerts});componentDidUpdate() {// called whenever prop value changed&nbsp;if(this.props.householdAlerts !== this.state.tableAlerts)&nbsp;&nbsp; &nbsp; &nbsp; this.setState({ tableAlerts: this.props.householdAlerts })}selectOngoingAlerts = (e, data) => {&nbsp;const { isChecked, tableAlerts } = this.state;&nbsp;this.setState( {isChecked : !isChecked} );&nbsp;// right now, { isChecked } still refer to construct abouve methond and prev value...&nbsp;// for more consist aproach, consider do the filtering logic direct at render without manipulate state&nbsp;if(!isChecked) {&nbsp;&nbsp; this.setState( { tableAlerts: tableAlerts.filter((alert) => alert.setTimestamp < alert.clearTimestamp)} )&nbsp;} else { this.setState({tableAlerts}) }}&nbsp;...rest class...}现在在渲染时,{ this.state.tableAlerts } 应该包含正确的信息

倚天杖

您可能应该使用componentDidUpdate. 它在每个状态和道具更改上运行。这是如何使用它的示例:componentDidUpdate(prevProps) {&nbsp;&nbsp; if(this.props.householdAlerts !== prevProps.householdAlerts) {&nbsp;&nbsp; &nbsp; this.setState({ tableAlerts: this.props.householdAlerts })&nbsp;&nbsp; }&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript