【问题标题】:Returning a promise object instead during retrieval在检索期间返回一个承诺对象
【发布时间】:2021-10-29 09:37:45
【问题描述】:

我有一个映射,并且在每个映射中我都想在文件存储 IPFS 中获取数据,例如名称。然后我想在界面上返回名称。但是,我得到一个“错误:对象作为 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>

【问题讨论】:

  • 如果你在这个函数中使用console.log,你会看到什么? const hName = hawkerDetails.then((details) => { console.log(details) });我想知道这个名字是否可以在 details.hName 或类似的东西上

标签: javascript reactjs promise axios ipfs


【解决方案1】:

有几件事情正在发生。

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

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

  3. 理想情况下,您希望创建一个数组of promises,然后然后使用Promise.all 处理数据。在我的示例中,我使用了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>
    })};
  </>
)

【讨论】:

  • 嗨,谢谢你的回答。但这仅适用于功能组件,对吗?因为我使用的是类组件。你知道我如何在类组件上做到这一点吗?
  • componentDidMount代替useEffect,并在构造函数中设置状态为this.state = { hawkers: [] };,然后在函数末尾使用this.setState({ hawkers })。然后,您可以在渲染中迭代 this.state.hawkers
猜你喜欢
  • 2015-11-27
  • 2020-01-04
  • 2015-06-05
  • 1970-01-01
  • 1970-01-01
  • 2014-10-05
  • 1970-01-01
  • 1970-01-01
  • 2016-09-18
相关资源
最近更新 更多