【问题标题】:Why is this not rendering from a map, in react为什么这不是从地图渲染,反应
【发布时间】:2020-10-11 09:42:23
【问题描述】:

所以我从数据库中获取项目并在之前将它们记录在控制台中,这样我就知道它们存在并且采用了我想要的格式。我还写了一个简单的方法来确保渲染工作。代码看起来像这样(为无关位简化了)

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 (
<div>
{renderSomething()}
</div>
)

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

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

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

测试成功了

【问题讨论】:

标签: reactjs rendering render


【解决方案1】:

渲染函数不能是一个承诺。您应该使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    相关资源
    最近更新 更多