所以我学会了反应,但我在练习时需要一些帮助。 这可能是一个很长的问题,但您的帮助将不胜感激。 以下代码都不起作用,所以我只想找出我做错了什么。 我设置了以下上下文,它是一个对象数组
import React, {createContext, useState} from 'react';
export const Songlist = createContext()
const TheSongs = (props) => {
const [songs, setSongs] = useState([
{title: "deliverance", artist: "opeth", id: 0},
{title: "civil war", artist: "guns n roses", id: 1},
{title: "heaven and hell", artist: "black sabbath", id: 2},
{title: "anesthetize", artist: "porcupine tree", id: 3}
])
const songList = () =>{
setSongs(songs.forEach(song =>{
return(
<div className="container" key={song.id}>
<h4>{song.title}</h4>
<h3>{song.artist}</h3>
</div>
)
}))
}
return (
<Songlist.Provider value={songs, songList}>
{props.children}
</Songlist.Provider>
);
}
export default TheSongs;
然后我尝试在这样的组件中调用它
import React, {useContext} from 'react';
import {Songlist} from '../contexts/TheWorld'
const SongListUI = () => {
const {songList} = useContext(Songlist)
return (
<div className="hi">
{songList}
</div>
);
}
export default SongListUI;
没有发生任何错误,但是根本没有渲染任何内容,并且名为"hi"的div不包含任何内容。
然后我只是将数组保留在上下文中,然后再次使用 Context 在组件中调用它,但这次我尝试了一些不同的东西,那就是
import React, {useContext} from 'react';
import {Songlist} from '../contexts/TheWorld'
const SongListUI = () => {
const {songs} = useContext(Songlist)
const songList = () =>{
songs.forEach(song =>{
return(
<div className="container" key={song.id}>
<h4>{song.title}</h4>
<h3>{song.artist}</h3>
</div>
)
})
}
return (
<div className="hi">
{songList}
</div>
);
}
export default SongListUI;
我收到一个错误,说函数不允许作为反应子项,并且在div 中仍然没有渲染任何东西,所以我再次尝试了一些不同的东西,我在jsx
内应用了forEach
循环而不是函数的名称,但它仍然不起作用,并且在"hi"div 中没有渲染任何东西。 所以我删除了整个上下文并在组件本身中使用了useState
钩子
import React, {useState} from 'react';
const SongListUI = () => {
const [songs, setSongs] = useState([
{title: "deliverance", artist: "opeth", id: 0},
{title: "civil war", artist: "guns n roses", id: 1},
{title: "heaven and hell", artist: "black sabbath", id: 2},
{title: "anesthetize", artist: "porcupine tree", id: 3}
])
const songlist = () =>{
setSongs(songs.forEach(song =>{
return(
<div className="container" key={song.id}>
<h4>{song.title}</h4>
<h3>{song.artist}</h3>
</div>
)
}))
}
return (
<div className="hi">
{songlist}
</div>
);
}
export default SongListUI;
由于反应子错误再次不起作用,所以
import React, {useState} from 'react';
const SongListUI = () => {
const [songs, setSongs] = useState([
{title: "deliverance", artist: "opeth", id: 0},
{title: "civil war", artist: "guns n roses", id: 1},
{title: "heaven and hell", artist: "black sabbath", id: 2},
{title: "anesthetize", artist: "porcupine tree", id: 3}
])
return (
<div className="hi">
{
songs.forEach(song =>{
return(
<div key={song.id}>
<h4>{song.title}</h4>
<h3>{song.artist}</h3>
</div>
)
})
}
</div>
);
}
export default SongListUI;
仍然没有任何效果,所以我只想知道我做错了什么......
forEach
的返回值为undefined
。你能试试你的最后一个例子,在你的歌曲中加入.map
吗?
即
songs.map((song) => <div key={song.id}><h4>{song.title}</h4><h3>{song.artist}</h3></div>)