【问题标题】:How to map out an array that is taken from props如何映射从 props 中获取的数组
【发布时间】:2022-11-30 14:28:38
【问题描述】:

我正在尝试绘制一个通过道具传递到组件中的数组。例如,我有一个 ViewPosts 页面,我通过将帖子作为 prop 传递到组件中来调用 Comments 组件。目标是从道具中取出数组并将其映射出来,以便我可以在 axios 调用中使用帖子 ID 来获取帖子的所有 cmets。然后,一旦我获取了 cmet,我需要能够从“评论”数组中取出用户 ID 并进行另一个 axios 调用以获取用户名(留下评论的人),因为后端开发人员没有包括那个在数组中。我还需要能够获取评论 ID 来调用 axios 来删除评论。我的代码如下

我成功映射了数组,但是,我在 return 语句中映射了它,因此不能在我的 axios 调用中使用数据,因为它在 return 语句之外。附上代码。

ViewPosts.js


{数据 && }


评论.js


导出默认函数 Comments(props) {

const [comments, setComments] = React.useState([]);
  React.useEffect(() => {
    axios
      .get(`http://localhost:6006/api/v1/posts/${props.post._id}/comments`)
      .then((res) => {
        console.log("Pulling Comments Frm::: ", res.data.data);
        setComments(res.data.data);
      })
      .catch((err) => console.log("err::  ", err));
  }, []); 
  const [user, setUser] = React.useState("")
  React.useEffect(() => {
    axios
      .get(`http://localhost:6006/api/v1/users/${comments.user}`)
      .then((res) => {
        setUser(res.data.data);
      })
      .catch((err) => console.log("err::  ", err));
  }, []); 
  return (
    <div>
        {comments?.map((comment) => (
            <>
                <Typography> <h3> {user.name}: {comment.text} </h3>  </Typography> 
            </>
        ))}
      
    </div>
  );
}


我知道我可能需要用 promise.all 和 array.map 做一些事情

【问题讨论】:

  • 查看帖子应该是:{data && <Comments post = {data} />

标签: javascript node.js reactjs material-ui


【解决方案1】:

Axios 调用是异步的,因此将在获取您的 cmets 之前调用用户 api 调用。

您可以将 comments 添加到用户 api useEffect 中,这样它看起来像
React.useEffect(() =&gt; { ... }, [comments]);
这样一来,只要 cmets 发生变化,就会进行调用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-23
    • 2018-09-13
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    • 2019-10-03
    • 2021-01-06
    • 1970-01-01
    相关资源
    最近更新 更多