简体   繁体   English

为什么我无法 map 我在 React 项目中的数据?

[英]Why am I unable to map my data in React project?

Ill be changing the key shortly.我很快就会更改密钥。 Using the code below I should be able to load a list of movies from the API and each movie should be linked to it's Provider Link website.使用下面的代码,我应该能够从 API 加载电影列表,并且每部电影都应该链接到它的 Provider Link 网站。 using the upMovieDetail.使用 upMovieDetail。 can anyone help point me in the right direction?谁能帮我指出正确的方向? I have a feeling it has something to do with the component being re-renderd after the click?我觉得它与单击后重新渲染的组件有关?

here is the codesandbox if you'd rather try to fix it here.. -- https://codesandbox.io/s/movieapp-searchbar-forked-qv1o6如果你想在这里修复它,这里是 codesandbox .. -- https://codesandbox.io/s/movieapp-searchbar-forked-qv1o6

const key ="fde5ddeba3b7dec3fc1f51852ca0fb95";

const getUpMovieDetail = (movieId) => {
     //const [movieId, setMovieId] = useState([]);

    const url = `https://api.themoviedb.org/3/movie/${movieId}/watch/providers?api_key=${key}`;
        return fetch(url);
      };
      
      function UpMovieDetail({ movieItem }) {
        const [searchLink, setSearchLink] = useState(null);
      
        useEffect(() => {
          getUpMovieDetail(movieItem.id)
            .then((res) => res.json())
            .then((res) => {
              setSearchLink(res?.results?.US?.link);
            });
        }, [movieItem.id]);

        return (
            <ul className="flexed-search">
    {searchLink.map((item) => 
    <div className="poster-container" key={item.id}>
    <li className="list-item">
        <a target="_blank" rel="noopener noreferrer" href={searchLink}
        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>
          );
        }; 


const SearchBar = () => {

const [search, setSearch] = useState([]);
const [input, setInput] = useState('');
 

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

};



//  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>
      <h1 className="row-label" tabIndex="0">Movies Related To Your Search</h1>
     </div>

 <div className="byName-container">
  {search.map((item) => (
    <UpMovieDetail key={item.id} movieItem={item} />
  ))}
</div>
 
 </div>
      )};

export default SearchBar;```


  [1]: http://codesandbox.io/s/movieapp-searchbar-forked-qv1o6
  [2]: https://codesandbox.io/s/movieapp-searchbar-forked-qv1o6

From the first render it throws the error because searchLink is null .从第一次渲染开始,它会抛出错误,因为searchLinknull Try this:试试这个:

{
  searchLink && searchLink.length && searchLink.map((item) =>
  ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我收到错误data.findIndex不是我的React with Redux项目中的函数? - Why am I getting the error data.findIndex is not a function in my React with Redux project? 为什么我无法在React组件中访问Mongo集合? - Why am I unable to access my Mongo collection in a React component? 我无法理解为什么我无法映射我在 React 程序中设置的状态下返回的数据 - I am having trouble understanding why I am not able to .map over the data I am return in the state that I set up in my React program 我无法安装我的项目套件 - I am unable to install my project packages 为什么我无法在json数据上调用.get /如何将json转换为地图 - Why am I unable to call .get on json data / how do I convert the json to a map 为什么我在系统中第一次运行 react js 项目时收到此错误消息? - Why I am getting this error message when I run react js project first time in my system? 为什么我的React组件无法提取我需要的库? - Why is my React component unable to pick up the library I am requiring? 在我的项目(随机报价生成器)中。 我无法排序问题? - In my Project (Random quote generator). I am unable to sort issue? 我的地图函数返回 React 组件时出错 - I am getting an error in my map function returning React component 为什么我在 React 应用程序中丢失了登录信息? - Why am I losing my login in my React App?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM