簡體   English   中英

我可以在componentDidMount中使用“ this.props”嗎? 錯誤:未被捕獲的TypeError:無法讀取未定義的屬性“映射”

[英]Can I use “this.props” in componentDidMount? Error:Uncaught TypeError: Cannot read property 'map' of undefined

在componentDidMount selectTodo分配給this.props.selected 在控制台中,我檢查selectTodo是否是包含comments數組的對象。 我正在嘗試進入此數組,但出現錯誤:錯誤:

未捕獲到的TypeError:無法讀取未定義的屬性“ map”

class Details extends Component {
  constructor() {
    super();


    this.state = {
      resul: []
      selectTodo:[]
    }; 
  }

  componentDidMount() {
    axios.get(" http://....../todos")
      .then(response => {
        this.setState({
          resul: response.data,
          selectTodo: this.props.selected
        });
      })
      .catch(error => {
        console.log('Error fetching and parsing data', Error);
      }
    );
  }


  render () {

    return (
      <div>    
        {
          { 
              this.state.selectTodo.comments.map((obj, i) => {
                return <li>{obj["comment"]}</li>
              })  
            } 
        }
      </div>      
    );
  }
}



export default Details;

CONSOLE.LOG

 console.log(this.state.selectTodo);


 return:


Object
  comments: (2) [{'comment': 'sdsd'}, {'comment': 'sdsdsdsds'}]
  id: 1

錯誤:未被捕獲的TypeError:無法讀取未定義的屬性“映射”

首先,您在staterender中定義的數據對我而言並不好。 我的意思是,您將selecTodo定義為constructor的數組,並嘗試在render方法中獲取為selectTodo.comments 因此,將狀態更改為

    this.state = {
      resul: []
      selectTodo:{comments: []}
    };

並將您在componentDidMount分配數據的方式更改為

  componentDidMount() {
    axios.get(" http://....../todos")
      .then(response => {
        this.setState({
          resul: response.data,
          selectTodo: { comments: this.props.selected.comments }
        });
      })
      .catch(error => {
        console.log('Error fetching and parsing data', Error);
      }
    );
  }

並在render執行以下操作

  render () {
    if(!this.state.selectedTodo.comments.length) {
      return null;
    }
    return (
      <div>    
        {
          { 
              this.state.selectTodo.comments.map((obj, i) => {
                return <li>{obj["comment"]}</li>
              })  
            } 
        }
      </div>      
    );
  }

未定義來自於componentDidMount在第一次渲染之后發生的事實,因此當第一次渲染發生時this.state.selectTodo仍然是未定義的。

解決此問題的一種方法是在渲染器內部檢查this.state.selectTodo是否存在,並且僅當存在該狀態時才返回帶有地圖的div,否則返回微調器或其他東西。

這有意義嗎?

暫無
暫無

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

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