簡體   English   中英

如何過濾Next.js中的道具? 無法從 Next.js 中的 componentDidMount 過濾道具中的數據

[英]How to filter props in Next.js? Can't filter data in props from componentDidMount in Next.js

我使用getStaticProps將數據放入組件的道具中。 然后我想在組件中使用該數據之前對其進行過濾。 通常我會在componentDidMount中執行此操作,但這是不可能的,因為看起來道具是在調用 componentDidMount 之后填充的。

解決此問題的最佳做法是什么?

這是我當前的代碼:

class Definition extends Component {
  constructor({ router }, ...props) {
    super(props);
    this.state = {
      songsArray: [],
    };
  }

  filterSpotifyResults = () => {
    const filteredArray = [];
    this.props.songsData.tracks.items.forEach((obj) => {
      if (obj.explicit === true) {
        return;
      } else {
        filteredArray.push(obj);
      }
    });
    this.setState({ songsArray: filteredArray });
  };

  componentDidMount = () => {
    this.filterSpotifyResults();
  };

  render() {
    if (this.props.router.isFallback) {
      return <h4>Loading...</h4>;
    }
    return (
      <div>
        <h3>this is where the definition will go</h3>
        <ul>
          {this.props.wordsData.definitions.map((obj, i) => (
            <li key={i}>{obj.definition}</li>
          ))}
        </ul>
        <iframe
          src={`https://open.spotify.com/embed/track/${this.props.songsData.tracks.items[0].id}`}
          width="300"
          height="380"
          allowtransparency="true"
          allow="encrypted-media"
        ></iframe>
      </div>
    );
  }
}

export default withRouter(Definition);

export async function getStaticProps(context) {
  const wordsRes = await fetch(
    `https://wordsapiv1.p.rapidapi.com/words/${context.params.word}/definitions`,
    {
      method: "GET",
      headers: {
        "x-rapidapi-key": process.env.NEXT_PUBLIC_DB_KEY,
        "x-rapidapi-host": "wordsapiv1.p.rapidapi.com",
      },
    }
  )
    .then((response) => {
      return response;
    })
    .catch((err) => {
      console.error(err);
    });
  const songsRes = await fetch(
    `https://api.spotify.com/v1/search?q=${context.params.word}&type=track`,
    {
      method: "GET",
      headers: {
        authorization:
          "Bearer " + process.env.NEXT_PUBLIC_ENV_SPOTIFY_ACCESS_TOKEN,
      },
    }
  )
    .then((response) => {
      return response;
    })
    .catch((err) => {
      console.error(err);
    });
  const wordsData = await wordsRes.json();
  const songsData = await songsRes.json();
  return {
    props: {
      wordsData,
      songsData,
      searchTerm: context.params.word,
    },
  };
}

最佳做法肯定是過濾服務器上的數據,這些數據已經在您的getStaticProps中。

所以把過濾移到那里,只返回你真正想要使用/渲染的數據。

暫無
暫無

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

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