【问题标题】:React.js- variable is empty when used in arrayReact.js-在数组中使用时变量为空
【发布时间】:2022-07-27 22:08:00
【问题描述】:

我正在尝试使组件数组根据数据库中的 ID 显示用户的用户名,如果用户不存在,则显示“已删除”。我的函数工作正常,并且值显示在日志中,但实际渲染的组件在值应该是的位置有一个空字符串。

postsList = this.state.postsArray.map(post => {
      var author = "";
      AccountService.getUsernameFromId(post.author, function(id, username) {
        author = username;
        console.log(author);
      });      
      return(
        <Item key={post._id}>
          <Item.Image size="small" src={post.image} />
          <Item.Content>
            <Item.Header as="a" href={"/blog/post/?id=" + post._id}>{post.name}</Item.Header>
            <Item.Meta>{author} | {post.date_created}</Item.Meta>
            <Item.Description>{post.post_contents.slice(0, 200) + "..."}</Item.Description>
          </Item.Content>
        </Item>
      );
    });

有人可以帮我解决这个问题吗?

【问题讨论】:

  • AccountService.getUsernameFromId 是异步函数吗?您是否正在向地图中的 API 服务器发出请求?

标签: reactjs


【解决方案1】:

我还不确定getUsernameFromId 是什么,但我觉得您正在尝试在地图期间向服务器发出 API 请求。

因此,在您向 API 发出请求的循环开始时,当 API 请求被解析时,组件无需等待 API 响应即可呈现,结果会被记录下来,这是预期的行为。

您必须将AccountService.getUsernameFromId 声明为异步函数或使其成为基于承诺的函数。

然后你可以这样写你的代码

postsList = this.state.postsArray.map(async post => {
  var author = await AccountService.getUsernameFromId(post.author);  
    
  return(
    <Item key={post._id}>
      <Item.Image size="small" src={post.image} />
      <Item.Content>
        <Item.Header as="a" href={"/blog/post/?id=" + post._id}>{post.name}</Item.Header>
        <Item.Meta>{author} | {post.date_created}</Item.Meta>
        <Item.Description>{post.post_contents.slice(0, 200) + "..."}</Item.Description>
      </Item.Content>
    </Item>
  );
});

【讨论】:

    【解决方案2】:

    这很正常,js 中的变量是按值复制而不是引用,因此当您更改在函数中创建的“作者”变量时,实际上是在更改变量“作者”的副本,因此不会更改实际变量.所以在你的整个程序中,作者将等于你在开头定义的一个空字符串。

    我的建议是,你使用钩子,特别是 useState 钩子,所以你的代码会是这样的:

    postsList = this.state.postsArray.map(post => {
      const [author, setAuthor] = useState([]);
      useEffect(() => {
      let auth = ""
      AccountService.getUsernameFromId(post.author, function(id, username) {
        auth = username;
        setAuthor(auth);
        console.log(auth);
      });
      }, [])
      return(
        <Item key={post._id}>
          <Item.Image size="small" src={post.image} />
          <Item.Content>
            <Item.Header as="a" href={"/blog/post/?id=" + post._id}>{post.name}</Item.Header>
            <Item.Meta>{author} | {post.date_created}</Item.Meta>
            <Item.Description>{post.post_contents.slice(0, 200) + "..."}</Item.Description>
          </Item.Content>
        </Item>
      );
    });
    

    【讨论】:

    • 从基于类的文件移动到钩子可能会让 OP 感到困惑,并且您可以在不重组文件以使用钩子的情况下获得相同的结果。
    猜你喜欢
    • 2022-07-13
    • 2011-09-03
    • 2022-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-24
    • 2015-09-05
    • 2020-07-03
    相关资源
    最近更新 更多