0
初めての反応とjavascript。私は今それを勉強しており、Reactクライアントのサーバーから文字列を取得して表示しようとしました。fetch()によって返された応答のテキストにアクセスするには?
const express = require('express');
const app = express();
app.set("port", process.env.PORT || 3001)
app.use(express.static("ayersapp/build"));
app.get('/message', (req, res) => {
res.send('Hello first respond!');
});
app.listen(app.get("port"));
App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Message from './message'
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
<Message />
</div>
);
}
}
export default App;
message.js
server.js以下のように私のコード私は.then使用して文字列データにアクセスすることができhereから
import React, {Component} from 'react';
class Message extends Component {
constructor(props) {
super(props);
this.state = {message: "abc"};
}
componentDidMount() {
fetch(`/message`).then(m=>{
this.setState(
{message: m.blob()}
);
});
}
render(){
const msg = this.state.message;
return <p>{msg}</p>;
}
}
export default Message;
(()=> {})。しかし、私はこのエラーが発生しました
Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
in p (at message.js:19)
in Message (at App.js:17)
in div (at App.js:9)
in App (at index.js:7)
私はどのようにオブジェクトPromiseの文字列にアクセスできるのか教えていただけますか?
を、それがテキストが –
@BingLanがコードを実証するための作業スニペットは – thedude
おかげ取り組んでいる追加定義されていません不平を言います! response.text()の前に 'return'を追加して動作させると、https://davidwalsh.name/fetchからダウンロードできます。 –