在检索期间返回一个 promise 对象

Returning a promise object instead during retrieval

我有一个映射,在每个映射中我想获取文件存储 IPFS 中的数据,例如名称。然后我要return界面上的名字。但是,我收到“错误:对象作为 React 子项无效(已找到:[object Promise])。如果您打算呈现子项集合,请改用数组。”有人可以帮帮我吗?几个小时以来一直试图解决这个问题。似乎无法理解为什么,因为我知道 hName 应该是一个字符串。

{this.props.hawkers.map((hawker, key) => {
          const hawkerDetails = axios
            .get("https://ipfs.infura.io/ipfs/" + hawker.profileHash)
            .then(function (response) {
              console.log("this is the data: ", response.data);
              return response.data;
            })
            .catch(function (error) {
              console.log(error);
            });

          const hName = hawkerDetails.then((details) => {
            return hName;
          });
 return (
            <>
              <h4 style={{ display: "flex", marginTop: 20 }}>
                <Link
                  to={`/hawkerInfo/${hawker.owner}`}
                  // state={{ chosenHawkerPk: hawker.owner }}
                  state={{ chosenHawkerPk: hawker }}
                >
                  {hName}
                </Link>
              </h4>

发生了几件事。

  1. 您没有使用 React state 来管理您的数据。

  2. 您将 details 作为参数传递给您的 then 方法,然后不使用它,因此 hName 没有意义。应该是details.hName.

  3. 理想情况下,您希望创建一个数组 of promises and then process the data with Promise.all. In my example I've used async/await

  4. 设置状态后,然后需要map处理return中的数据以创建HTML.

// Initialise state
const [ hawkers, setHawkers ] = useState([]);

// Async function called by the `useEffect` method
async function getData() {

  // Create a list of Axios promises
  const promises = this.props.hawkers.map(hawker => {
    const url = `https://ipfs.infura.io/ipfs/${hawker.profileHash}`;
    return axios.get(url);
  });

  // Wait for all the data to return
  const responses = await Promise.all(promises);

  // Use `map` to return a new array of each response's data
  const hawkers = data.map(response => response.data);

  // Set the state with that array
  setNames(hawkers);
}

// useEffect runs once if you pass in an empty
// array dependency
useEffect(() {
  getData();
}, []);

if (!hawkers.length) return <div>Loading</div>;

// Now just `map` over the data that you put in state
return (
  <>
    {hawkers.map(hawker => {
      <h4>
        <Link to={`/hawkerInfo/${hawker.details.owner}`}>
          {hawker.details.name}
        </Link>
      </h4>
    })};
  </>
)