Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何将this.state.songs更新为歌曲列表_Reactjs_State - Fatal编程技术网

Reactjs 如何将this.state.songs更新为歌曲列表

Reactjs 如何将this.state.songs更新为歌曲列表,reactjs,state,Reactjs,State,我无法更新需要从歌曲列表中获取值的州歌曲。如何将歌曲更新到songsList?这与组件生命周期有关吗?运行下面的代码时,会出现“songsList is undefined”错误。const songList在渲染中 import React, { Component } from 'react'; import logo from './components/Logo/box8.png'; import './App.css'; import SearchBox

我无法更新需要从歌曲列表中获取值的州歌曲。如何将歌曲更新到songsList?这与组件生命周期有关吗?运行下面的代码时,会出现“songsList is undefined”错误。const songList在渲染中

    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;
import React,{Component}来自'React';
从“/components/logo/box8.png”导入徽标;
导入“/App.css”;
从“./components/SearchBox/SearchBox”导入SearchBox;
从“./components/SongCards/SongCards”导入歌曲卡;
输入‘超光速子’;
从“axios”导入axios;
类应用程序扩展组件{
状态={
歌曲:[],
搜索字段:“”,
条目:[]
};
componentDidMount(){
axios.get(`https://itunes.apple.com/in/rss/topalbums/limit=100/json`)
。然后(响应=>
{this.setState({entries:response.data.feed.entry});
});
}
onSearchChange=(事件)=>{
this.setState({songs:songsList})
this.setState({searchField:event.target.value})
const filteredSongs=this.state.songs.filter(song=>{
return song.title.toLowerCase()包括(this.state.searchField.toLowerCase())
});
}
render(){
const songsList=this.state.entries.map(entries=>{
返回(
);
});
返回(
{songsList}
);
}
}
导出默认应用程序;

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

    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;
尝试使用下面更正的代码

    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;
  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())
        });
     }

您已经提到,
this.state.entries
是一个
对象

如果这是真的,那么你就不能对它执行
.map
,因为
.map
是一种
数组
方法

    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;
但是,您可以使用获取
[key,value]
this.state.entries
的数组

    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;
Object.entries(this.state.entries).map(([key,value]) => ...)
简单的运行示例:

    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;
constobject1={foo:'这是foo',baz:'这是baz'};

Object.entries(object1.map(([key,value])=>console.log(`key:${key},value:${value}`)所以我会这样做:

    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;
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>
    );
  }
}
const IN_PROGRESS='IN_PROGRESS';
const SUCCESS=‘SUCCESS’;
类应用程序扩展组件{
状态={
歌曲:空,
条目:null,
状态:空
};
componentDidMount(){
this.setState({status:IN_PROGRESS});
axios.get(`https://itunes.apple.com/in/rss/topalbums/limit=100/json`)
。然后({data}=>{
const songs=data.feed.entry;
this.setState({entries:songs});
这个.setState({songs});
this.setState({status:SUCCESS});
});
}
onSearchChange=({target})=>{
常量{value}=目标;
const songs=this.state.entires.filter(歌曲=>
song.title.toLowerCase().includes(value.toLowerCase())
});
这个.setState({songs});
}
render(){
const{status,songs}=this.state;
返回(
{
状态===正在进行中(&U)
(/*您可以在此处插入某种类型的加载器,指示数据正在加载*/)
}
{
状态===SUCCESS&&songs.map(条目=>{
常数{
id,['im:artist']:artist,['im:image']:image,
['im:price']:价格,['im:releaseDate']:日期,标题
}=入口;
返回(
)
}
}
{
//如果状态==失败,您可以在此处显示错误消息
}
);
}
}
  • 当组件挂载时,我将状态设置为IN_PROGRESS(如果您希望某种加载程序显示),并且数据正在被提取-
    axios。get
    是异步的,所以请记住,当数据被提取时,render方法已经被触发。当数据被加载时,然后在状态下我持有两个变量,
    条目
    ,它持有未过滤的歌曲列表,而
    歌曲
    则持有过滤的歌曲
  • 当触发
    search
    时,我将按搜索短语过滤
    entires
    ,并将其设置为该过滤数组的状态
  • 组件通过过滤的歌曲呈现歌曲卡映射

  • 谢谢你的回复,我终于做到了

        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;
    
    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;
    
    import React,{Component}来自'React';
    从“/components/logo/box8.png”导入徽标;
    导入“/App.css”;
    从“./components/SearchBox/SearchBox”导入SearchBox;
    从“./components/Albums/Albums”导入相册;
    从“./components/Scroll/Scroll”导入滚动;
    输入‘超光速子’;
    从“表情词典”导入表情符号;
    从“axios”导入axios;
    类应用程序扩展组件{
    状态={
    秀:假,,
    歌曲:[],
    搜索字段:“”,
    };
    componentDidMount(){
    axios.get(`https://itunes.apple.com/in/rss/topalbums/limit=100/json`)
    。然后(响应=>
    {this.setState({songs:response.data.feed.entry});
    });
    }
    itunesPageLoader=()=>{
    this.setState({show:false})
    }
    onSearchChange=(事件)=>{
    this.setState({searchField:event.target.value})
    }
    render(){
    const filteredSongs=this.state.songs.filter(song=>{
    返回
    song.title.label.toLowerCase().includes(this.state.searchField.toLowerCase())
    })
    返回(
    ©2018年Box8有限公司,所有
    保留权利
    {`Made with${emoji.getUnicode(“紫心”)由Renjith`}
    );
    }
    }
    导出默认应用程序;
    
    您的确切问题是什么?歌曲列表未定义?您的this.state.entri