前提・実現したいこと
ReactとRailsを使用しています。SuperAgentでapiから情報を取り、componentDidMountでthis.stateに情報を格納したいのですができません。
発生している問題・エラーメッセージ
this.stateに格納されない。
該当のソースコード
class MessagesBox extends React.Component {
constructor(props) {
super(props)
this.state = {
messages: [],
}
}
getMessages() {
request
.get(APIEndpoints.MESSAGES) // getリクエスト'/api/messages'
.end((error, res) => {
if (!error && res.status === 200) {
const json = JSON.parse(res.text)
this.setState({
messages: json.messages,
})
} else {
console.log(error)
}
})
}
componentDidMount() {
this.getMessages()
}
render() {
const messagesLength = this.state.messages.length
}
試したこと
render {
request
.get('/api/messages')
.end((error, res) => {
if (!error && res.status === 200) {
console.log(JSON.parse(res.text))
} else {
console.log(error)
}
})
}
上記のコードを記載してconsoleをみるとデータは格納されています。
しかし、this.stateには格納されません。
補足情報(FW/ツールのバージョンなど)
"react": "^0.14.5",
回答1件
あなたの回答
tips
プレビュー