单击按钮时,数字增加1

时间:2018-07-29 06:05:40

标签: node.js mongodb reactjs express

在点击事件中尝试使数字增加1, 想知道什么是正确的方法?

在我的render()中:

{this.state.posts.map((post, i) =>
     <div key={post._id}>

         <span>Votes: {post.votes}</span>


         <a href="" onClick={() => this.votePost(post._id, i)}>
             Click Me
         </a>
     </div>
 )}

初始状态:

state = {
    posts: [],
};

点击功能:

votePost = async id => {
    await axios.put(`/posts/${id}`);

    this.setState({

    })
};

后端:

router.put('posts/:post_id', async (req, res, next) => {
try {
    const { post_id } = req.params;
    const { votes } = req.body;

    const doc = await Post.findByIdAndUpdate(post_id, { votes });
    res.status(200).send(doc);
} catch (e) {
    next(e);
}
});

2 个答案:

答案 0 :(得分:0)

要将数字增加1,您可以使用以下代码。

constructor() {
    this.state = {
        count: 0
    }
}


handleOnCLick = () => {
  this.setState((prevState) => (count: prevState.count + 1))
}

<button onClick={this.handleOnCLick}/>

答案 1 :(得分:0)

如果要更改状态数组的特定条目的值,则需要在渲染循环中跟踪索引:

{this.state.posts.map((post, i) =>
     <div key={post._id}>

         <span>Votes: {post.votes}</span>


         <a href="" onClick={() => this.votePost(post._id, i)}>
             Click Me
         </a>
     </div>
 )}

因此,您可以在自己的pollPost函数中更改正确帖子的值

votePost = async (id, index) => {

    await axios.put(`/posts/${id}/upvote` /*or downvote*/);

        ....

    });

    // Update your state like this:
    this.setState(({posts})=>{
       posts[index] = newPostData;
       return posts
    });
}

编辑:

对于后端,您最终可以创建两个端点/upvote/downvote

const vote = (req, res, next)=>{
    try {
       const { post_id } = req.params;
       const doc = await Post.findByIdAndUpdate(post_id, ({ votes })=>({votes: req.voteup ? votes + 1 : votes - 1});
       res.status(200).send(doc);
   } catch (e) {
    next(e);
   }
}

router.put('posts/:post_id/upvote', async (req, res, next) => {
    req.voteup = true;
    vote(req, res, next);
});

router.put('posts/:post_id/downvote', async (req, res, next) => {
    req.voteup = false;
    vote(req, res, next);
});