Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
746 views
in Technique[技术] by (71.8m points)

javascript - ReactJS falsely claims a string is an object and refuses to render

Setup and environment: App is created with create-react-app, contained in App.js, and run using npm start at the command line.

Obligatory source code:

import React from 'react';
import ReactDOM from 'react-dom';
import logo from './logo.svg';
import './App.css';

async function getRemoteData() {
  var result = [];
  const response = await fetch('some.site.that.returns.json'); // not the actual URL although you get the idea
  const json = await response.json();
  for (const entry of json.entry) {
    result.push(json.fullUrl);
    console.log(json.fullUrl);
  }
  console.log("String representation");
  console.log(result.toString());
  // Following commented string used to test ReactJS functionality
  // return "";
  return result.toString(); 
}

// minimalist self-explanatory class that dumps a message to the browser
class Message extends React.Component {
    render() {
      return (
        <div>
          <h2>{this.props.text}</h2>
        </div>
      );
    }
}

function App() {
  return ReactDOM.render(<Message text={getRemoteData()} />, document.getElementById('root'));
}

export default App;

This only produces an unhelpful, untraceable error:

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 h2 (at App.js:23) in div (at App.js:22) in Message (at App.js:31)

First, getRemoteData should not be return a Promise at all. It should return a string - painfully obvious from the return statement. I'm using kudlajz's answer in Fetch: set variable with fetch response and return from function - using await to fix the asynchronous aspect and then returning the underlying value.

Next, I set up getRemoteData to return an empty string on purpose - test ReactJS. Same result If it's claiming an empty string is an invalid object, that's a serious problem. Next, this provides absolutely no info on what's going wrong. Any ideas how to get this to work? Why is an Object (rather than a string) being returned at all?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

getRemoteData is an async function. It returns a Promise, which is an object.

To deal with asynchronous data, you need to store the result in the state and use that instead.

See also the React FAQ: AJAX and APIs


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...