简体   繁体   中英

How to access text in respond returned by fetch()?

New to React and javascript. I am studying it now and I tried to get a string from server in React client and display it. My code as below

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;

from here I can access the string data by using .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?

try this:

 fetch('https://jsonplaceholder.typicode.com/posts/1') .then(response => response.text()) .then(text => { console.log('text = ', text) // this.setState({ // message: text // }) }) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM