Javascript 如何获取电影ID';并使用它们来获取数据,从而为我提供指向其提供商的链接?

Javascript 如何获取电影ID';并使用它们来获取数据,从而为我提供指向其提供商的链接?,javascript,html,reactjs,Javascript,Html,Reactjs,首先让我为自己糟糕的格式化能力道歉。其次,我知道那里真的很乱。随着事情变得越来越复杂,在正确布局这段代码的情况下也变得越来越复杂。也就是说,这就是我目前所处的位置 我使用了三个不同的API链接来收集3个不同状态的数据。一个是搜索结果,另一个是趋势,另一个是即将发布的。在我展示了它的许多有用数据之后,我想添加一个功能,在这个功能中,我可以点击任何电影图像并被带到我可以购买或观看电影的网站。 MovieDatabase APi有另一个链接,但是您需要在链接中包含${movieID}。此链接将为您提供

首先让我为自己糟糕的格式化能力道歉。其次,我知道那里真的很乱。随着事情变得越来越复杂,在正确布局这段代码的情况下也变得越来越复杂。也就是说,这就是我目前所处的位置

我使用了三个不同的API链接来收集3个不同状态的数据。一个是搜索结果,另一个是趋势,另一个是即将发布的。在我展示了它的许多有用数据之后,我想添加一个功能,在这个功能中,我可以点击任何电影图像并被带到我可以购买或观看电影的网站。
MovieDatabase APi有另一个链接,但是您需要在链接中包含${movieID}。此链接将为您提供有关在何处观看或购买电影的实际链接的数据。我想获得这个链接,并设置每个电影与他们自己的供应商链接。(将您带到可以观看或购买电影的网站的链接)。所以我想我应该开始尝试在流行电影中这样做。
为了做到这一点,我想我可以进入趋势电影的useEffect调用,并获取为趋势电影设置的状态,如果电影ID为,则获取一个数组。我使用trending.map((item)=>setMovieId(item.ID));然后我创建了一个名为ProviderLink的新函数,并将该movieId作为参数添加到该链接中,该链接将为我提供每个个人电影的ProviderLink。(告诉你在哪里购买或观看电影的链接)…我再次使用这个新的movieId参数获取了新的链接,现在在链接中,我获得了数据,我将其设置为一个新状态,并尝试在我渲染所有电影的下方的锚定标记中应用该状态。我将每个电影列表项包装在一个
中,认为这样可以为每个电影设置适当的提供者链接。但它不工作…我收到一个错误,告诉我它无法获取,它甚至没有在列表中包含ID,好像我也需要它。如果您需要API密钥来试用,请告诉我。或者在moviedatabase网站停下来,快速抓取一个

import React, {useState, useEffect} from 'react';

const SearchBar = () => {

const [search, setSearch] = useState([]);
const [input, setInput] = useState('');
const [trending, setTrending] = useState([]);
const [upcoming, setUpcoming] = useState([]);
const [providerlink, setProviderlink] = useState('');
 const [movieId, setMovieId] = useState([]);

 

// Input Field
const onUserInput = ({target}) => {
    setInput(target.value);

};


// On page load Fetch trending movies
useEffect(() => { 

    const trendUrl = "https://api.themoviedb.org/3/trending/movie/week?api_key=fde5ddeba3b7dec3fc1f51852ca0fb95";
fetch(trendUrl)
.then((response) => response.json())
.then((data) => {
   setTrending(data.results);
})
.catch((error) => {
    console.log('Error!! Data interupted!:', error)
});
 
trending.map((item) => setMovieId(item.id));


}, [trending]);


// MovieProviderLink
useEffect(() => { 
    const url = 
    `https://api.themoviedb.org/3/movie/${movieId}/watch/providers?api_key=fde5ddeba3b7dec3fc1f51852ca0fb95`;
    fetch(url)
    .then((res) => 
      res.json()
    ).then((res) =>  
         setProviderlink(res.results));

  //Gives movie ID and adds it to properlink
    
}, [movieId]);



useEffect(() => {
    const upcomingUrl = "https://api.themoviedb.org/3/movie/upcoming?api_key=fde5ddeba3b7dec3fc1f51852ca0fb95";

    fetch(upcomingUrl)
    .then((response) => response.json())
    .then((data) => {
       setUpcoming(data.results);
    })
    .catch((error) => {
        console.log('Error!! Data interupted!:', error)
    });
});


//  Api Call 
const SearchApi = (event) => {
    const aUrl = "https://api.themoviedb.org/3/search/movie?api_key=fde5ddeba3b7dec3fc1f51852ca0fb95";
   const newUrl = aUrl +'&query=' + input;
 event.preventDefault();
       
    fetch(newUrl)
    .then((response) => response.json())
    .then((data) => {
       setSearch(data.results);
        
    })
    .catch((error) => {
        console.log('Error!! Data interupted!:', error)
    })

    };
    
      return (
        //   Heading
<div>
    <div className="container">
        <h1>Movie Search Extravaganza!</h1>

        {/* Input Field and Button Form */}
      <form onSubmit={SearchApi}>
        <input value={input} onChange={onUserInput} type="text"  className="searchbar" aria-label="searchbar" placeholder="search" required/>
        <br></br>
        <button type="submit"  aria-label="searchbutton" className="searchBtn">Movie Express Search</button>
      </form>
     </div>



    <div className="byName-container">
        <h1 className="row-label" tabIndex="0">Movies Related To Your Search</h1>
      <ul className="flexed-search">
          
          {search.map((item) => 
          <div className="poster-container" key={item.id}>
          <li className="list-item">
              <a href="www.google.com" onclick={((event) => {event.preventDefault()})}>
           <img className="image-element"  tabIndex="0" alt="movie poster" title={`--Title: ${item.title}--  --Description:    ${item.overview}--  --Vote Average: ${item.vote_average}`} aria-label={item.title} src={`https://image.tmdb.org/t/p/w500${item.poster_path}`} />
           </a>
          <h3 className="posterTitle">{item.title}</h3>
          </li>
          </div>
       )}
      </ul>
        </div>
 

<div className="trending-container">
    <h1 className="row-label" tabIndex="0">This Weeks Trending Tittles</h1>
    <ul className="flexed-trending">
    {trending.map((it) => 
    
    <div className="poster-container" key={it.id}>
        <a href={providerlink}>
    <li className="list-item"> <img className="image-element" tabIndex="0" aria-label={it.title} title={`--Title: ${it.title}--  --Description:    ${it.overview}--  --Vote Average: ${it.vote_average}`} alt="movie poster" src={`https://image.tmdb.org/t/p/w500${it.poster_path}`} />
     <h3 className="posterTitle">{it.title}</h3>
     
    </li>
    </a>
    </div>
    
    )}
    </ul>
</div>


<div className="upcoming-container"> 
<h1 className="row-label" tabIndex="0">Upcomming Movies</h1>
 <ul className="flexed-upcoming">
 {upcoming.map((inn) => 
 <div className="poster-container" key={inn.id}>
 <li className="list-item">
 <img className="image-element" tabIndex="0" alt="movie poster" aria-label={inn.title} title={`--Title: ${inn.title}--  --Description:    ${inn.overview}--  --Vote Average: ${inn.vote_average}`} src={`https://image.tmdb.org/t/p/w500${inn.poster_path}`} />

 <h3 className="posterTitle">{inn.title}</h3>
 </li>
 </div>
 )}
 </ul>


</div>
        

        </div>


    )
};

export default SearchBar;```
import React,{useState,useffect}来自“React”;
常量搜索栏=()=>{
const[search,setSearch]=useState([]);
const[input,setInput]=useState(“”);
常量[trending,setTrending]=useState([]);
const[coming,setUpcoming]=useState([]);
const[providerlink,setProviderlink]=useState(“”);
const[movieId,setMovieId]=useState([]);
//输入字段
常量onUserInput=({target})=>{
设置输入(目标值);
};
//页面加载获取趋势电影
useffect(()=>{
常量趋势URL=”https://api.themoviedb.org/3/trending/movie/week?api_key=fde5ddeba3b7dec3fc1f51852ca0fb95";
获取(趋势URL)
.then((response)=>response.json())
。然后((数据)=>{
设置趋势(数据、结果);
})
.catch((错误)=>{
console.log('错误!!数据中断!:',错误)
});
trending.map((项)=>setMovieId(项.id));
},[趋势];
//电影提供商链接
useffect(()=>{
常量url=
`https://api.themoviedb.org/3/movie/${movieId}/watch/providers?api_key=fde5ddeba3b7dec3fc1f51852ca0fb95`;
获取(url)
。然后((res)=>
res.json()
)。然后((res)=>
setProviderlink(res.results));
//提供电影ID并将其添加到PropertLink
},[movieId]);
useffect(()=>{
常量upcomingUrl=”https://api.themoviedb.org/3/movie/upcoming?api_key=fde5ddeba3b7dec3fc1f51852ca0fb95";
获取(upcomingUrl)
.then((response)=>response.json())
。然后((数据)=>{
设置(数据、结果);
})
.catch((错误)=>{
console.log('错误!!数据中断!:',错误)
});
});
//Api调用
const SearchApi=(事件)=>{
const aUrl=”https://api.themoviedb.org/3/search/movie?api_key=fde5ddeba3b7dec3fc1f51852ca0fb95";
const newUrl=aUrl+'&query='+input;
event.preventDefault();
获取(新URL)
.then((response)=>response.json())
。然后((数据)=>{
setSearch(数据、结果);
})
.catch((错误)=>{
console.log('错误!!数据中断!:',错误)
})
};
返回(
//标题
电影搜索盛典!
{/*输入字段和按钮表单*/}


电影快车搜索 与您的搜索相关的电影
    {search.map((项目)=>
  • {item.title}
  • )}
本周流行的标题
    {trending.map((it)=> )}
上流电影
    {即将到来的.map((inn)=>
  • {inn.title}
  • )}
) }; 导出默认搜索栏```
您必须围绕从API调用获得的JSON数组创建一个循环,以显示所需的内容。例如,如果您有一个带有趋势的部分,您可以循环浏览趋势JSON数组,并以您想要的结构显示内容。我不知道返回值,但您可能可以执行类似于
{movie.name}
之类的操作。在初始循环中,您可以创建另一个循环,该循环通过提供者API进行迭代

糖代码表示法如下所示:

var trendingMoviesContainer = document.querySelector('your_selector_here');
var html = "";
for(let movie in trending_array){
    html += '<div ....>{movie.id}</div>';
    html += '<div ...>{movie.name}</div>';
    //etc...
    let providersUrl = "https://api.themoviedb.org/3/movie/{movie.id}/watch/providers?api_key="
    // rest of your fetch data logic...
    
    for(let provider in providers_array) {
        html += '<div ...>{provider.name}</div>';
        html += '<div ...>{provider.link}</div>';
        //etc...
    }
    // inject trending movies structure into container
    trendingMoviesContainer.append(html); 
}
var trendingMoviesContainer=document.querySelector(“您的选择器”在这里);
var html=“”;
for(让电影进入趋势阵列){
html+='{movie.id}';
html+='{movie.name}';
//等等。。。
让providersUrl=”https://api.themoviedb.org/3/movie/{movie.id}/watch/providers?api_key=”
//其余的获取数据逻辑。。。
for(让提供程序\u数组中的提供程序){
html+='{provider.name}';
html+='{provider.link}';
//等等。。。
}
//将趋势电影结构注入cont