【问题标题】:React rendering trello card namesReact 渲染 trello 卡名称
【发布时间】:2017-02-04 08:51:41
【问题描述】:

我有一个 react 应用程序,它有一个这样的组件:

import React, { Component } from 'react';
import '../css/TrelloCards.css';

class TrelloCards extends Component {
  componentDidMount() {
    const authenticationFailure = () => { console.log('Auth failure') };
    const trello = window.Trello;

    const getCards = () => {
      const error = (error) => {
        console.log(error);
      }
    const cards = (cards) => {
      console.log(cards);
    }
    trello.get('/member/me/cards', cards, error);
  }

  trello.authorize({
      type: 'redirect',
      name: 'React Trello',
      scope: {
        read: 'true',
        write: 'true' },
      expiration: 'never',
      success: getCards,
      error: authenticationFailure,
      response_type: 'token',
    });
  }

  render() {
    return(
      <h1>Placeholder</h1>
    );
  }
}

export default TrelloCards;

我已经成功地在控制台记录了我的卡片,但现在我想在页面上呈现它们,我已经尝试过

render() {
  return(
    <ul>
      {cards}
    </ul>
  );
}

我尝试过通过如下卡片进行映射:

cards.map(card => {
  return(
    <li>{card.name}</li>
  );
}

但我收到未定义“卡片”的错误。总的来说,我对 React 和编程很陌生,任何帮助都将不胜感激。

【问题讨论】:

    标签: reactjs trello


    【解决方案1】:

    在您的情况下,render 无法访问您通过 trello 下载的 cards(它们只能在 componentDidMount 中访问)。解决此问题的一种方法是将下载的卡片保存到反应状态。然后将调用render,因为状态已更改并且卡片将被渲染。

    示例

    class TrelloCards extends Component {
      constructor() {
        this.state = {
          cards: []      <-------- define your initial state
        }
      }
    
      componentDidMount() {
        const trello = window.Trello;
    
        trello.authorize({
          type: 'redirect',
          name: 'React Trello',
          scope: {
            read: 'true',
            write: 'true' },
          expiration: 'never',
          success: () => console.log('auth success'),
          error: () => console.log('auth failure'),
          response_type: 'token',
        });
    
        trello.get('/member/me/cards', 
          (cards) => this.setState({ cards }),
                          ^----  set state here (shorthand)
          (error) => console.log('could not get cards'))
        }
      }
    
      render() {
        return(
          <div>
            {this.state.cards.map(card =>
              <li>{card.name}</li>)}
              ^---- render cards from state
          </div>
        );
      }
    }
    

    【讨论】:

    • 太棒了,谢谢!在 console.log('could not get cards') 之后缺少一个 ')' 但除此之外一切都很好。
    • 已修复。很好的收获。
    猜你喜欢
    • 2015-05-25
    • 2020-10-20
    • 2015-07-12
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多