[英]How to access text in respond returned by fetch()?
New to React and javascript. React和javascript的新手。 I am studying it now and I tried to get a string from server in React client and display it. 我现在正在研究它,我试图从React客户端的服务器中获取一个字符串并显示它。 My code as below 我的代码如下
server.js 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 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 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;
from here I can access the string data by using .then(()=>{}). 从这里,我可以使用.then(()=> {})访问字符串数据。 But I got this error 但是我得到这个错误
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)
Could anyone let me know how I can access the string in object Promise? 谁能让我知道如何访问Promise对象中的字符串?
try this: 尝试这个:
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.