子组件没有被渲染 - React

时间:2021-03-04 13:37:43

标签: javascript reactjs frontend state react-lifecycle

我正在学习 React 课程,目前正在学习 React 的生命周期方法。到目前为止,我已经能够使用 componentDidMount 调用 API 并设置状态。但是,我似乎无法让卡片组件在卡片列表 div 中显示图像。我确定我做对了(循环遍历 state 并使用 props 创建 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;

2 个答案:

答案 0 :(得分:2)

您的地图功能:

const cards = this.state.drawn.map(c => {
    <Card image={c.image} key={c.id} name={c.name} />
})

不返回任何内容。所以这段代码的结果是一个undefined数组。

您有两个选择:

  1. 添加return
const cards = this.state.drawn.map(c => {
    return <Card image={c.image} key={c.id} name={c.name} />
})
  1. 用 () 包裹,而不是 {}:
const cards = this.state.drawn.map(c => (
    <Card image={c.image} key={c.id} name={c.name} />
))

答案 1 :(得分:0)

你应该返回地图内的卡片组件

 const cards = this.state.drawn.map(c => {
            return <Card image={c.image} key={c.id} name={c.name} />
        })
相关问题