为什么这不是从地图渲染,反应

Why is this not rendering from a map, in react

所以我从数据库中获取项目并且 console.log 就在之前,所以我知道它们存在并且是我想要的格式。我还写了一个简单的方法来确保渲染工作。代码看起来像这样(对不相关的部分进行了简化)

const renderSomething = () => {
getFromDB().then(function(data){
if (data) {
            console.log(data.something)  //returns an array in console          
          return data.something.map(somet => { 
                console.log(' somet is ' + somet) //return somet with quotes: ""              
                return <p>{somet}</p>
            })
        } else {
            console.log("No data!");
        }
}
}

然后在 return:

   return (
<div>
{renderSomething()}
</div>
)

屏幕上什么也没有出现。我做了一个测试以确保它应该:

const basic = () => {
    return ['abc', 'bca'].map(num =>  <h1>{num}</h1>)
}

 return (
        <div>
           {basic()}
        </div>
    )

测试成功

渲染功能不能是承诺。您应该使用 Effect 方法从 api 下载数据,然后使用 State 为组件设置它。

import React, { Fragment, useState, useEffect } from "react";
import ReactDOM from "react-dom";

function LiveVisitors() {
  const [visitors, setVisitors] = useState([
    {
      ip: "",
      countryCode: "",
      city: "Warsaw",
      state: "",
      country: "Poland"
    },
    {
      ip: "",
      countryCode: "",
      city: "Gdańsk",
      state: "",
      country: "Poland"
    }
  ]);
  const { ip, countryCode, city, state, country } = visitors;

  useEffect(() => {
    getUserData();
  }, []);

  const getUserData = () => {
    //imitate fetch
    setVisitors([
      ...visitors,
      {
    ip: "",
    countryCode: "",
    city: "Wrocław",
    state: "",
    country: "Poland"
      }
    ]);
  };

  return (
    <div>
      {visitors.map((el) => (
    <div>{el.city}</div>
      ))}
    </div>
  );
}

const wrapper = document.getElementById("container");
ReactDOM.render(<LiveVisitors />, wrapper);

这是您可以玩的互动版本。 https://codesandbox.io/s/react-playground-forked-hqswi?file=/index.js:0-947