我的問題是我想制作一個喜歡,不喜歡,壁爐等按鈕,但我的問題是我計算的點擊量會將其上傳到資料庫但我必須重新加載它才能顯示給客戶端邊。
這是我的示例代碼。
對于后端
router.route('/update/:id').post((req,res) => {
practice1.findById(req.params.id)
.then( practice_1 => {
practice_1.name = req.body.name
practice_1.number = req.body.number
practice_1.save()
.then(() => res.json('Sample Updated!'))
.catch(err => res.status(400).json('Error :' err))
})
.catch()
})
router.route('/update/:id').put((req,res) => {
practice1.findByIdAndUpdate(req.params.id)
.then(practice_1 => {
practice_1.name = req.body.name
practice_1.number = req.body.number
practice_1.save()
.then(() => res.json('Sample Updated!'))
.catch(err => res.status(400).json('Error :' err))
})
.catch(err => res.status(400).json('Error :' err))
})
我確實嘗試在 post() 中執行此操作,但它的作業原理與 put() 相同,它僅在我重新加載頁面后才更新。這是前端的代碼。
import axios from 'axios'
import React, { useEffect, useState } from 'react'
const Samples = props => (
<tr>
<th>{props.sample._id}</th>
<th>{props.sample.name}</th>
<th>{props.sample.number}</th>
<th>
<button onClick={e => props.addMore(props.sample._id,props.sample)}> Add number </button>
</th>
</tr>
)
function ListSample() {
const [samples,setSamples] = useState([])
// const [sampleadd,setSampleAdd] = useState(0)
useEffect(() => {
axios.get('http://localhost:1212/practice1')
.then(data => setSamples(data.data))
.catch(err => console.log(err))
},[])
const addMore = (id,samples) => {
samples.number = 1
axios.post('http://localhost:1212/practice1/update/' id,{ name:samples.name , number: samples.number })
.then(res => console.log(res.data))
.catch(err => console.log(err))
axios.put('http://localhost:1212/practice1/update/' id, { name: samples.name, number: samples.number} )
.then(res => console.log(res.data))
.catch(err => console.log(err))
}
const sampleDeclarations = () => {
return samples.map(currentsample => {
return <Samples
key={currentsample._id}
sample={currentsample}
addMore={ e => addMore(e,currentsample)}
></Samples>
})
}
return (
<div>
<h1> Sample List </h1>
<table>
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
{sampleDeclarations()}
</tbody>
</table>
</div>
)
}
export default ListSample
所以基本上我在addMore()如你所見的部分中所做的我示例添加samples.number = 1然后給它放置或發布..您可以注釋掉放置或發布 axios..我已經嘗試過了..但我基本上想要自動上傳我的喜歡計數而無需重新加載。
這張圖基本上是這樣的。
是的,對命名感到抱歉,但不介意……我只想以正確的方法執行它。
uj5u.com熱心網友回復:
由于這是一個狀態掛鉤,因此您必須使用 setSamples。在你做 samples.number = 1 之后,嘗試做
setSamples({
...samples,
number = samples.number 1
});
...samples 物件在哪里傳播以獲取原始樣本的其余值,而您只是更改了 number 引數。此外,可能將 useState([]) 的內部從一個空陣列更改為一個空物件 {},因為 samples 似乎是一個物件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/444647.html
上一篇:編輯器中顯示的垂直線
