反应useState和map()

时间:2019-12-30 23:31:02

标签: javascript reactjs

我正在尝试从地图上输入评论, 但是由于我使用相同的useState,因此所有输入字段都会更改。 如何定位特定的输入?

return (
  <div>
    {posts.map(post => (
      <div key={post.id}>
        <img
          src={`https://localhost:1111/api/posts/uploads/images/${post.content}`}
          alt={`${post.id}`}
        />
        <p>{post.description}</p>
        <span>{post.likes ? post.likes : 0}</span>
        <button onClick={() => like(post.id)}>Like</button>
        <Link to={`/post/${post.id}`}>Edit</Link>
        <button onClick={() => deletePost(post.id)}>Delete</button>
        <form onSubmit={uploadComment}>
          <input
            type="text"
            onChange={handleComment}
            value={comment}
            placeholder="Comment"
          />
        </form>
      </div>
    ))}
  </div>
)

2 个答案:

答案 0 :(得分:0)

考虑对每个输入使用react useState挂钩。

答案 1 :(得分:0)

每个呈现的帖子都有自己的状态,这意味着它是自己组件的用例:

remove_emojis <- function(string)
{
  intToUtf8(utf8ToInt(string)[-which(utf8ToInt(string) > 100000)])
}

remove_emojis(x)
#> [1] "moises q folgado u hoje tá rolando goulash quarta tem linguiça acebolada e sexta tem carne assada até rimou httpstcodijgcydex6 httpstco0utmufUinscrição é só chegar se liga na programação  httpstcou7uVod6ltcancjme de saúde httpstcojwr1yt5r9l httpstcodc9doaAo4amebz4fyFmmmmmmm"

然后您的渲染函数将如下所示:

function Post(post, deletePost) {
  const [comment, setComment] = useState('');
  const uploadComment = () => {}; // your code is missing
  return (
      <div key={post.id}>
        <img
          src={`https://localhost:1111/api/posts/uploads/images/${post.content}`}
          alt={`${post.id}`}
        />
        <p>{post.description}</p>
        <span>{post.likes ? post.likes : 0}</span>
        <button onClick={() => like(post.id)}>Like</button>
        <Link to={`/post/${post.id}`}>Edit</Link>
        <button onClick={() => deletePost(post.id)}>Delete</button>
        <form onSubmit={uploadComment}>
          <input
            type="text"
            onChange={e => setComment(e.target.value)}
            value={comment}
            placeholder="Comment"
          />
        </form>
      </div>
  )
}