我使用本機反應。
這就是我想要使用的功能。這里最重要的一點是editCommentMutation。
為了執行這個突變,它需要兩個變數,它們是id和payload。
const onUpdateComment = React.useCallback((commentId) => {
setEdit(true);
console.log(commentId, comments);
editCommentMutation({
variables: {
id: parseInt(commentId),
payload: comments,
},
});
}, []);
我正確地得到了這兩個變數。

對于id,我從組件螢屏中獲取它。所以它通過了argument。因為payload,我在同一個螢屏上得到它。
這里的問題是當我按下 時button1,它會將commentId(id)資料從組件螢屏發送到此頁面。
當我按下 時,它會在此頁面上button2發送資料。comments(payload)
在這個應用程式上,我按button1并按順序寫評論,然后按 button2。
所以每個資料不是在一起,而是一個接一個。
所以我執行console.log(commentId, comments),
- 按下按鈕1:
386 undefined - 按下按鈕2:
undefined Object { "comments": "??", }
它undefined肯定有.. 但是為了執行突變,我需要兩個資料。
為此,我想我需要將即將到來的資料保存在某個地方。
我也試過了
const [data, setData] = useState("")。
在我將commentId 保存到這里之后:
setData(commentId)。
但它沒有被保存,只是消失了。:)
你能幫助我嗎?
uj5u.com熱心網友回復:
這是一個最小的可驗證示例。運行下面的代碼并
- 單擊??以編輯其中一條評論
- 單擊?以保存您的編輯并查看更新的評論
function App() {
const [edit, setEdit] = React.useState(null)
const [comments, setComments] = React.useState([ "hello", "?????" ])
const onEdit = editable => event => { setEdit(editable) }
const onUpdate = newComment => event => {
/* execute your graphql mutation here */
setComments([
...comments.slice(0, edit.index),
newComment,
...comments.slice(edit.index 1)
])
setEdit(null)
}
return <div>
{comments.map((comment, index) =>
<p>{comment}
<button
children="??"
onClick={onEdit({comment, index})}
disabled={Boolean(edit)}
/>
</p>
)}
{edit ? <EditComment text={edit.comment} onUpdate={onUpdate} /> : null}
</div>
}
function EditComment({ text, onUpdate }) {
const [value, setValue] = React.useState(text)
return <div>
<input value={value} onChange={e => setValue(e.target.value)} />
<button onClick={onUpdate(value)} children="?" />
</div>
}
ReactDOM.render(<App/>, document.querySelector("#app"))
button[disabled] { opacity: 0.5; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.14.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.14.0/umd/react-dom.production.min.js"></script>
<div id="app"></div>
在您的應用程式中,您將在onUpdate. ?可以使用輕松定義取消按鈕const onCancel = event => { setEdit(null) }并將其傳遞給EditComment.
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/429489.html
上一篇:SpringBoot-SpringSecurity-InvalidBearerTokenException錯誤處理
