我可以在 componentDidMount 中使用“this.props”吗?

在 componentDidMount 中selectTodo,将this.props.selected. 在控制台中,我检查 selectTodo 是一个包含comments. 我正在尝试访问此数组,但出现错误:错误:


未捕获的类型错误:无法读取未定义的属性“地图”


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(this.state.selectTodo);



 return:



Object

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

  id: 1

错误:未捕获的类型错误:无法读取未定义的属性“地图”


LEATH
浏览 257回答 2
2回答

慕斯709654

首先,您在其中定义state和循环的数据render对我来说不太好。我的意思是,您将selecTodo数组定义为 inconstructor并尝试selectTodo.comments在render方法中获取。因此,将状态更改为&nbsp; &nbsp; this.state = {&nbsp; &nbsp; &nbsp; resul: []&nbsp; &nbsp; &nbsp; selectTodo:{comments: []}&nbsp; &nbsp; };并更改您分配数据的componentDidMount方式&nbsp; componentDidMount() {&nbsp; &nbsp; axios.get(" http://....../todos")&nbsp; &nbsp; &nbsp; .then(response => {&nbsp; &nbsp; &nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; resul: response.data,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; selectTodo: { comments: this.props.selected.comments }&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; .catch(error => {&nbsp; &nbsp; &nbsp; &nbsp; console.log('Error fetching and parsing data', Error);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; );&nbsp; }并在 render&nbsp; render () {&nbsp; &nbsp; if(!this.state.selectedTodo.comments.length) {&nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; }&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.state.selectTodo.comments.map((obj, i) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return <li>{obj["comment"]}</li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; );&nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript