首页 > 解决方案 > ES6 将 url 附加到数组中的映射对象

问题描述

我正在使用 React 进行一个辅助项目,并且正在使用 tmdb API。

我的 GET 请求

performSearch = () => { // Requesting data from API
    axios.get(`${URL}api_key=${API_KEY}&language=en-US&query=${this.state.searchInput}${PARAMS}`)
        .then((res) => {
            console.log(res.data.results);
            this.setState({ searchResults: res.data.results});
        });
}

我像这样使用 map 函数渲染结果

 const Suggestions = (props) => {
  const options = props.searchResults.map(r => (
    <li className='search-results'
      key={r.id} >
      {r.title}
      {r.name}
      {r.poster_path}
    </li>
  ))
  return <ul>{options}</ul>
}

export default Suggestions

我需要的是这个 URL ' https://image.tmdb.org/t/p/w300 ' + {r.poster_path} 来渲染图像,我该怎么做呢?最终结果看起来像这样' https://image.tmdb.org/t/p/w300/gwPSoYUHAKmdyVywgLpKKA4BjRr.jpg '

标签: javascriptreactjsapiecmascript-6get

解决方案


您可以将其作为属性传递给 img 对象。例如,使用模板字符串:

 const Suggestions = (props) => {
   const options = props.searchResults.map((r) => (
     <li className='search-results' key={r.id}>
       {r.title}
       {r.name}
       <img src={`https://image.tmdb.org/t/p/w300/${r.poster_path}`} alt={r.title} />
     </li>
   ))
   return <ul>{options}</ul>
 };

 export default Suggestions

推荐阅读