簡體   English   中英

從api獲取的數據不會作為prop傳遞給嵌套組件

[英]data fetched from api is not passed as props to nested component

在我的React App中,我有一個主要的App組件,在其中我從componentDidMount方法中的api中獲取數據並將其保存為狀態。 然后,我將該狀態傳遞給App中的另一個組件。 但是,當我使用prop中的數據時,它顯示為未定義。 我沒有遇到的另一個奇怪之處是,當我在App組件中的console.log狀態渲染方法時,我首先得到一個空數組,然后第二個是其中包含數據的另一個數組。 請在這里幫助我代碼如下:

class App extends React.Component {
    constructor() {
        super();
        this.state = {
            data: []
        };
    }

    componentDidMount() {
        this.fetchData();
    }

    fetchData() {
        fetch(
            `https://api.themoviedb.org/3/movie/popular?api_key=${
                process.env.REACT_APP_API_KEY
            }&language=en-US&page=1`
        )
            .then(res => res.json())
            .then(data => {
                this.setState({ data });
            })
            .catch(err => console.log(err));
    }

    render() {
        console.log(this.state.data);
        return (
            <div>
                <Movie title="Popular" results={this.state.data} />
            </div>
        );
    }
}

export default App;

在Movie組件中未定義this.state.data,就像這樣

function Movie(props) {
  return (
    <p>{props.data.results[0].title}</p>
  )
}

您正在將resultstitle作為props傳遞給<Movie>組件,但仍試圖獲取data道具。

零件:

<Movie title="Popular" results={this.state.data} />

因此,您需要獲取results屬性,而不是數據。

固定:

function Movie(props) {
  return (
    <p>{props.results[0].title}</p>
  )
}

additionaly:

如果您已經通過了標題道具,為什么不只使用該道具作為標題呢?

function Movie(props) {
  return (
    <p>{props.title}</p>
  )
}

您的支持就是results因此您需要在組件中引用它:

function Movie(props) {
  return (
    <p>{props.results[0].title}</p>
  )
}

在您的App組件中,您可能還想添加一個簽入render以顯示加載消息或微調框,如果該組件在最初渲染時尚未解決數據加載問題:

if (!this.state.data.length) return <Spinner />;

暫無
暫無

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

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