【问题标题】:How to increase increase database attribute by one by making a get request to the database from Reactjs如何通过从 Reactjs 向数据库发出 get 请求来增加数据库属性
【发布时间】:2020-10-29 07:24:30
【问题描述】:

我正在研究 Mernstack。我有一个名为 Events 的模型,Events 有标题、描述、startingDate 和 closingDate 属性。当一个事件被创建时,人们可以通过点击一个按钮来表明他们正在参加这个事件,这个按钮将通过将数字增加 1 来更新该事件中名为going 的另一个属性。这仅适用于 Node 和 Expressjs,但现在我正在将 React 集成到 Node 中,我不知道如何让它工作。

现在我的问题是,如何通过单击链接从 React 向 My Express 路由发出 GET 请求,以便 Event 模型中的 going 属性增加一?

这是我的活动路线

 router.get("/:id/going", async (req, res, next) => {
   Event.findById(req.params.id, function(err, event) {
      if (!event) {
       return next(new Error('Could not load Document'));
      }else {
      event.going += 1;
      event.save();
      res.json(event)
     }
   });
});

这是我在 Reactjs 中的构造函数。 注意:我的 Event 和 EventComment 工作正常,我只是在寻找一种方法,每当点击链接时,将事件内的 go 属性值增加 1。

 constructor(props) {
    super(props);
    this.state = {
        eventcomments: [],
        event: '',
        name: '',
        description:'',
        going: '',

    };
}

我想用来触发事件路由的 GET 请求将数字增加 1

 axios.get('http://localhost:9000/events/'+this.props.match.params.id+'/going')
    .then(res => {
        this.setState({
            going: '',
        })
    })

这是我希望用户单击的链接,以使 Event 路由中的 going 属性增加 1

<Link to={"/events/"+this.state.event._id+"/going"}>Going</Link>

【问题讨论】:

    标签: node.js reactjs express


    【解决方案1】:

    由于您的端点正在使用更新的going 属性返回更新的事件记录,因此只需使用该值设置状态。

    axios.get('http://localhost:9000/events/'+this.props.match.params.id+'/going')
    .then(res => {
        this.setState({
            going: res.data.going
        })
    })
    

    如果res.data.going 是返回值的形状。

    【讨论】:

    • 谢谢@Splitty 我会试试的。主要问题是当我点击链接时,路线根本没有被击中,我不知道为什么链接没有击中路线
    • 哦,我明白你现在在问什么了。 &lt;Link ... &lt;/&gt; 元素会将用户导航到 /going 页面。只需让当前页面使用componentDidMount 生命周期方法或等效挂钩来触发axios.get 调用。
    【解决方案2】:

    谢谢各位。我已经设法让它工作了。 这就是我所做的。

      updateGoing = going => {
        axios.get('http://localhost:9000/events/'+this.props.match.params.id+'/going')
        .then(response => {
            his.setState({event: response.data})
    });
    

    并将其从链接更改为按钮

    <button onClick={() => this.updateGoing(this.state.event._id)}> Going </button>
    

    【讨论】:

      猜你喜欢
      • 2020-10-07
      • 1970-01-01
      • 2016-04-05
      • 2020-01-07
      • 1970-01-01
      • 2011-08-22
      • 2018-10-13
      • 2019-06-26
      • 2021-06-03
      相关资源
      最近更新 更多