我有一个反应应用程序,它有一个组件:
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和编程很新,一般都会有任何帮助。
答案 0 :(得分:0)
在您的情况下,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>
);
}
}