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;
来自here我可以使用.then(()=&gt; {})访问字符串数据。但是我收到了这个错误
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中的字符串吗?
答案 0 :(得分:1)
试试这个:
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.text())
.then(text => {
console.log('text = ', text)
// this.setState({
// message: text
// })
})