javascript - 子组件未渲染 - React
问题描述
我正在学习反应课程,目前正在学习反应的生命周期方法。到目前为止,我已经能够使用 componentDidMount 调用 API 并设置状态。但是,我似乎无法让卡片组件在卡片列表 div 中显示图像。我确定我做对了(循环遍历状态并使用道具创建 Card 组件)。
import react, {Component} from 'react';
import axios from 'axios';
import Card from './Card';
const api = ' https://deckofcardsapi.com/api/deck/';
class CardList extends Component {
state = {
deck: '',
drawn: []
}
componentDidMount = async() => {
let response = await axios.get(`${api}new/shuffle`);
this.setState({ deck: response.data })
}
getCards = async() => {
const deck_id = this.state.deck.deck_id;
let response = await axios.get(`${api}${deck_id}/draw/`);
let card = response.data.cards[0];
this.setState(st => ({
drawn: [
...st.drawn, {
id: card.code,
image: card.image,
name: `${card.value} of ${card.suit}`
}
]
}))
}
render(){
const cards = this.state.drawn.map(c => {
<Card image={c.image} key={c.id} name={c.name} />
})
return (
<div className="CardList">
<button onClick={this.getCards}>Get Cards</button>
{cards}
</div>
)
}
}
export default CardList;
import react, {Component} from 'react';
class Card extends Component {
render(){
return (
<img src={this.props.image} alt={this.props.name} />
)
}
}
export default Card;
import CardList from './CardList';
function App() {
return (
<div className="App">
<CardList />
</div>
);
}
export default App;
解决方案
你的地图功能:
const cards = this.state.drawn.map(c => {
<Card image={c.image} key={c.id} name={c.name} />
})
不返回任何东西。所以这段代码的结果是一个数组undefined
。
你有两个选择:
- 添加
return
:
const cards = this.state.drawn.map(c => {
return <Card image={c.image} key={c.id} name={c.name} />
})
- 换成 (),而不是 {}:
const cards = this.state.drawn.map(c => (
<Card image={c.image} key={c.id} name={c.name} />
))
推荐阅读
- netlogo - 在特定补丁中更改 1 只海龟的海龟品种
- django - Django 编辑或删除表中的选定行 - ListView
- spring-boot - 我是spring boot的新手,请帮我解决这个问题
- git - 如何添加新的本地分支来跟踪 GitHub 页面(gh-pages)创建的远程分支?
- mongodb - 从一列复制到另一列时替换字符mongodb
- javascript - 控制台中出现“Uncaught TypeError: Cannot read property 'addEventListener' of null”
- c++ - 如何从另一个班级访问朋友功能?
- python - 结构相同的三个模型的不同过拟合
- listview - 自动调整 ListView 大小
- c++ - 如何在 C++ 中正确打印 unicode 字符?