无法访问ComponentDidMount方法内部的道具

时间:2020-10-01 06:53:33

标签: reactjs api axios

大家好,我是React JS的新手,当我尝试在componentDidMount方法中访问我的网址时,出现诸如“无法正确读取道具”之类的n错误,请尝试解决我的错误

App.js

import React from 'react';
import './App.css';
import Row from './Row';
import Request from './Request';

 class App extends React.Component {
  constructor(){
    super();
  }

  render() {
    return (
      <div className='App'>
        <h1>Welcome to Netflix Clone</h1>
        <Row title='NETFLIX ORIGINALS' fetchUrl={Request.fetchNetflixOriginals}/>
        <Row title='TRENDING NOW' fetchUrl={Request.fetchTrending}/>
        <Row title='TOP RATED' fetchUrl={Request.fetchTopRated}/>
        <Row title='ACTION MOVIES' fetchUrl={Request.fetchActionMovies}/>
        <Row title='COMEDY MOVIES' fetchUrl={Request.fetchComedyMovies}/>
        <Row title='HORROR MOVIES' fetchUrl={Request.fetchHorrorMovies}/>
        <Row title='ROMANCE MOVIES' fetchUrl={Request.fetchRomanceMovies}/>
        <Row title='DOCUMENTARIES' fetchUrl={Request.fetchDocumentarie}/>
      </div>
    )
  }
}

export default App

Row.js这是我要访问访存URL的代码

import React from 'react';
import Axios from './Axios';

 class Row extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            // movie:[],
        }
    }

    componentDidMount(){
        async function fetchData(){
            const request = await Axios.get(this.props.fetchUrl);
            console.log(request);
            return request;
        }
        fetchData();
    }

    render() {
        return (
            <div>
              <h3> {this.props.title}</h3> 
            </div>
        )
    }
}

export default Row;

1 个答案:

答案 0 :(得分:1)

我建议不要将componentDidMount与async一起使用,因为该方法属于react生命周期。

相反,您可以这样做

import React from 'react';
import Axios from './Axios';

 class Row extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            // movie:[],
        }
    }

    fetchData = async () => {    
        const request = await Axios.get(this.props.fetchUrl);
        console.log(request);
        return request;
    }

    componentDidMount(){
        this.fetchData();
    }

    render() {
        return (
            <div>
              <h3> {this.props.title}</h3> 
            </div>
        )
    }
}

export default Row;