[英]How to access text in respond returned by fetch()?
React和javascript的新手。 我現在正在研究它,我試圖從React客戶端的服務器中獲取一個字符串並顯示它。 我的代碼如下
server.js
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
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;
從這里,我可以使用.then(()=> {})訪問字符串數據。 但是我得到這個錯誤
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對象中的字符串?
嘗試這個:
fetch('https://jsonplaceholder.typicode.com/posts/1') .then(response => response.text()) .then(text => { console.log('text = ', text) // this.setState({ // message: text // }) })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.