【问题标题】:How can I update the this.state.songs to songsList如何将 this.state.songs 更新为歌曲列表
【发布时间】:2019-02-26 10:17:18
【问题描述】:

我无法更新需要从 songList 获取值的状态歌曲。如何将歌曲更新到 songList ?它与组件生命周期有关吗?运行以下代码时,会抛出“songsList is undefined”错误。 const songList 在 render 中。

    import React, { Component } from 'react';
    import logo from './components/Logo/box8.png';
    import './App.css';
    import SearchBox from './components/SearchBox/SearchBox';
    import SongCards from './components/SongCards/SongCards';
    import 'tachyons';
    import axios from 'axios';

    class App extends Component {
          state = {
            songs : [],
          searchField: '',
          entries: []
          };



      componentDidMount() {
          axios.get(`https://itunes.apple.com/in/rss/topalbums/limit=100/json`)
          .then(response => 
            {this.setState({ entries: response.data.feed.entry });

          });
        }

    onSearchChange=(event)=>{
      this.setState({songs : songsList})
        this.setState({searchField : event.target.value})
        const filteredSongs = this.state.songs.filter(song =>{
          return song.title.toLowerCase().includes(this.state.searchField.toLowerCase())
        });
     }

       render(){

          const songsList = this.state.entries.map(entries => {
          return (
            <SongCards 
              key={entries.id.label} 
              artist={entries["im:artist"].label}
              image={entries["im:image"][2].label}
              link={entries.id.label}
              price={entries["im:price"].label}
              date={entries["im:releaseDate"].label}
              title={entries.title.label}
            />
          );
        });



        return (
          <div className="App">

            <header className="App-header">
              <img src={logo} className="App-logo" alt="logo" />
            </header>
            <SearchBox searchChange= {this.onSearchChange}/>
            {songsList}


      </div>
    );
  }
}

export default App;

【问题讨论】:

  • 您的具体问题是什么?歌曲列表未定义?您的 this.state.entries 看起来如何?你能做控制台日志并更新有问题的数据,以便我们检查吗
  • 它是一个包含歌曲详细信息的对象对象类别:{ id: {label: "itunes.apple.com/in/album/aravindha-sameth...inal-motion-picture-soundtrack-ep/1436841209?uo=2", im:artist: {标签:“Thaman S.”,属性:{...}} im:contentType:{im:contentType:{...},im:image:(3)im:itemCount:{label:“4”} im:name: {label:“Aravindha Sametha(电影原声带)-EP”} im:price:{label:“₹60”,im:releaseDate:{label:“2018-09-20T00:00:00-07:00” , 版权:{label:“℗ 2018 Zee Music Company”} 标题:{label:“Aravindha Sametha (Original Motion Picture Soundtrack)”}
  • 你能把这些数据放在你的问题中吗?你也没有确认你的确切问题
  • 由于格式问题,我无法将此对象数据放入问题中。我想将 this.state.songs 更新为我为 const songList 获得的输出。
  • 我想在搜索字段中搜索到的歌曲

标签: reactjs state


【解决方案1】:

感谢您的所有回复。我终于成功了。

import React, { Component } from 'react';
import logo from './components/Logo/box8.png';
import './App.css';
import SearchBox from './components/SearchBox/SearchBox';
import Albums from './components/Albums/Albums';
import Scroll from './components/Scroll/Scroll';
import 'tachyons';
import emoji from 'emoji-dictionary';
import axios from 'axios';

class App extends Component {
      state = {
        show:false,
        songs : [],
      searchField: '',
      };


  componentDidMount() {
      axios.get(`https://itunes.apple.com/in/rss/topalbums/limit=100/json`)
      .then(response => 
        {this.setState({songs:response.data.feed.entry });
         });
    }

itunesPageLoader=()=>{
  this.setState({show:false})
}

onSearchChange=(event)=>{
    this.setState({searchField : event.target.value})

 }

   render(){

    const filteredSongs = this.state.songs.filter(song =>{
      return 
 song.title.label.toLowerCase().includes(this.state.searchField.toLowerCase())
    })

 return (

      <div className="App">


        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
        </header>
        <SearchBox searchChange= {this.onSearchChange}/>
        <Scroll >
        <Albums songs={filteredSongs}/>
        </Scroll>
        <footer className="pv4 ph3 ph5-m ph6-l red">
            <small className="f6 db tc">© 2018 <b className="ttu">Box8 Inc</b>., All 
     Rights Reserved</small>
            <div className="tc mt3">
               {`Made with  ${emoji.getUnicode("purple_heart")} by Renjith`}
            </div>
        </footer>


      </div>
    );
  }
}

export default App;

【讨论】:

    【解决方案2】:

    试试这个。您实际上是使用 setState 将歌曲列表分配给歌曲,但歌曲列表在 onSearchChange 中不存在。要将搜索到的值推送到数组,您需要将 event.target.value 推送到歌曲数组

    尝试使用以下更正的代码

      onSearchChange=(event)=>{
           this.setState(prevState => ({songs : [...prevState.songs, event.target.value]}));
            this.setState({searchField : event.target.value})
             const filteredSongs = this.state.songs.filter(song =>{
             return song.title.toLowerCase().includes(this.state.searchField.toLowerCase())
            });
         }
    

    【讨论】:

    • 感谢您的快速响应。在进入 onsearchchange 之前,我想要 state.songs 中的所有对象
    • 谁能建议我在 react javascript 应用程序中更好的标题文本动画?我想为我的应用添加一个很酷的标题文本。
    【解决方案3】:

    您提到this.state.entriesObject
    如果这是真的,那么你不能对它执行.map,因为.mapArray 方法。

    但是,您可以使用Object.entries 来获取[key,value]this.state.entries 的数组。

    Object.entries(this.state.entries).map(([key,value]) => ...)
    

    简单运行示例:

    const object1 = { foo: 'this is foo', baz: "this is baz" };
    Object.entries(object1).map(([key,value]) => console.log(`key: ${key}, value: ${value}`));

    【讨论】:

      【解决方案4】:

      所以我会这样做:

      const IN_PROGRESS = 'IN_PROGRESS';
      const SUCCESS = 'SUCCESS';
      
      class App extends Component {
        state = {
          songs : null,
          entries: null,
          status: null
        };
      
        componentDidMount() {
           this.setState({status: IN_PROGRESS});
      
           axios.get(`https://itunes.apple.com/in/rss/topalbums/limit=100/json`)
            .then({data} => {
              const songs = data.feed.entry;
      
              this.setState({entries: songs});
              this.setState({songs});
              this.setState({status: SUCCESS});
            });
          }
      
        onSearchChange = ({target}) => {
          const {value} = target;
      
          const songs = this.state.entires.filter(song => 
            song.title.toLowerCase().includes(value.toLowerCase())
          });
      
          this.setState({songs});
        }
      
        render() {
          const {status, songs} = this.state;
      
          return (
            <div className="App">
              <header className="App-header">
                <img src={logo} className="App-logo" alt="logo" />
              </header>
      
              <SearchBox searchChange={this.onSearchChange}/>
      
              {
                 status === IN_PROGRESS && 
                  (/* you can insert here some kind of loader which indicates that data is loading*/)
              }
      
              {
                 status === SUCCESS && songs.map(entry => {
                   const {
                     id, ['im:artist']: artist, ['im:image']: image,
                     ['im:price']: price, ['im:releaseDate']: date, title
                   } = entry;
      
                   return (
                     <SongCard
                       key={id.label} 
                       artist={artist.label}
                       image={image[2].label}
                       link={id.label}
                       price={price.label}
                       date={date.label}
                       title={entry.title.label}
                     />
                   )
                 }
              }
      
              {
                 //Here you can display error message if status === FAILURE
              }
            </div>
          );
        }
      }
      
      1. 当组件确实挂载时,我将状态设置为 IN_PROGRESS(如果您希望显示某种加载程序),并且正在获取数据 - axios.get 是异步的,因此请记住,当获取数据时,渲染方法已经被触发。加载数据后,在状态下我保存两个变量,entries 保存未过滤的歌曲列表,songs 保存过滤后的歌曲。
      2. search 被触发时,我会按搜索到的短语过滤entires,并将此过滤后的数组设置为状态。
      3. 组件通过过滤songs 渲染songCards 映射

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-15
        • 2016-07-01
        相关资源
        最近更新 更多