【问题标题】:ES6 Attaching a url to a mapped object from an arrayES6 将 url 附加到数组中的映射对象
【发布时间】:2018-11-21 03:32:06
【问题描述】:

我正在使用 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'

【问题讨论】:

  • 图片应该在哪里?在
  • ?
  • 您不应该将URL + {r.poster_path} 传递给图像标签的 src 属性吗?
  • 标签: javascript reactjs api ecmascript-6 get


    【解决方案1】:

    您可以将其作为属性传递给 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
    

    【讨论】:

    • 该死,看起来我已经很接近了,我只需要那个$谢谢兄弟
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签