簡體   English   中英

在獲取數據之前,Console.log()顯示未定義

[英]Console.log() shows undefined before getting data

我似乎有一個生命周期鈎子問題,我似乎無法解決。

export default class EditRevision extends Component {

  state = {
    data: [],
    customColumns: []
  }

  componentWillMount = () => {
      axios.get('http://localhost:8080/lagbevakning/revision/subscriptions?id=' + (this.props.match.params.id)).then(response => {
        this.setState({
          data: response.data,
          loading: false
        })
      })
  }

  render() {
    /* THIS IS THE CONSOLE.LOG() I AM REFERRING TO */
    console.log(this.state.data.subscriptionRevisionDTOS) 
    return (  
      <div></div>
    )
  }
}

這是我在渲染組件時的日志 https://i.gyazo.com/9dcf4d13b96cdd2c3527e36224df0004.png CONSOLE.LOG()

它是未定義的,然后按照我的意願檢索數據,然后它再次未定義。

非常感謝有關導致此問題的原因的任何建議,謝謝。

替換這個:

componentWillMount = () => {
    axios.get('http://localhost:8080/lagbevakning/revision/subscriptions?id=' + (this.props.match.params.id)).then(response => {
        this.setState({
            data: response.data,
            loading: false
        })
    })

有:

constructor(props){
    super(props)
    this.state = {
        data: [],
        customColumns: []
    }

    axios.get('http://localhost:8080/lagbevakning/revision/subscriptions?id=' + (this.props.match.params.id)).then(response => {
        this.setState({
            data: response.data,
            loading: false
        })
    })
}

嘗試在構造函數或componentDidMount()中調用axios(不應使用componentWillMount)。 未定義的結果是由異步調用引起的。 看起來你有很多不受控制的渲染。 嘗試添加一個shouldComponentUpdate函數或在PureComponent中轉換您的組件

看看https://reactjs.org/docs/react-component.html

export default class EditRevision extends Component {

  state = {
   data:{subscriptionRevisionDTOS:[]},
   customColumns: []
 }

 componentDidMount = () => {
  axios.get('http://localhost:8080/lagbevakning/revision/subscriptions?id=' + 
  (this.props.match.params.id)).then(response => {
    this.setState({
      data: response.data,
      loading: false
    })
  })

  render() {
    /* THIS IS THE CONSOLE.LOG() I AM REFERRING TO */
    console.log(this.state.data.subscriptionRevisionDTOS) 
    return (  
      <div></div>
    )
  }

看到這應該是這樣的

你有初始狀態

state = {
    data: [],
    customColumns: []
 }

這里this.state.data是空數組,它沒有subscriptionRevisionDTOS的定義,這就是為什么你得到this.state.data.subscriptionRevisionDTOS undefined

同時,您的async axios.get調用已完成, this.state.data已使用subscriptionRevisionDTOS更新。

一旦state更新,再次調用render()並獲得this.state.data.subscriptionRevisionDTOS的正確值。

所以線下肯定會有效。

state = {
   data:{subscriptionRevisionDTOS:[]},
   customColumns: []
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM