![](/img/trans.png)
[英]How to manage state in Edit Modal Form with Submit Function in React?
[英]React form state mutated by submit function
我正在自學 React,並使用 Axios API 構建一個小型的單頁 React 應用程序。 我有一個不斷失敗的 POST 請求。 console.log
廣泛使用似乎表明表單輸入的狀態正在以某種方式被提交函數改變,盡管我不知道為什么。 幫助!
這是代碼:
import React, { useState, useEffect } from 'react'
import axios from 'axios'
import { Grid, TextField, Button, Typography } from '@material-ui/core'
import { FaHome } from 'react-icons/fa'
const AddItem = ({ setShowAddItem }) => {
const [inputs, setInputs] = useState()
const [submitted, setSubmitted] = useState(false)
useEffect(() => {
console.log(`Type: ${typeof inputs} Data: ${inputs}`)
if (inputs) {
console.log('executing POST')
console.log(`Inside if() Type: ${typeof inputs} Data: ${inputs}`)
axios.post('/api/ItemModels', { ...inputs })
.then(res => {
console.log(res.data)
})
.catch(err => console.error(err))
setInputs()
setSubmitted(false)
}
}, [submitted])
const handleInputChange = event => {
setInputs({ ...inputs, [event.target.name]: event.target.value })
console.log(inputs)
console.log(typeof inputs)
}
const handleSubmit = event => {
console.log("handleSubmit triggered")
if (event) {
console.log("if() in handleSubmit triggered")
console.log(`Inside handleSubmit Data: ${inputs}`)
event.preventDefault()
setSubmitted(true)
}
}
return (
<>
<Grid container className="form-container">
<Typography variant="h3">Add an Item</Typography>
<form noValidate onSubmit={handleSubmit}>
<TextField name="shape" label="Shape" onChange={handleInputChange} required />
<TextField name="size" label="Size" onChange={handleInputChange} required />
<TextField name="color" label="Color" onChange={handleInputChange} required />
<TextField name="clarity" label="Clarity" onChange={handleInputChange} required />
<TextField name="price" label="Price" onChange={handleInputChange} required />
<TextField name="listPrice" label="List Price" onChange={handleInputChange} required />
<Button type="submit">
Submit
</Button>
</form>
</Grid>
<Button type="button" onClick={() => setShowAddItem(false)}>
<FaHome />
</Button>
</>
)
}
export default AddItem
這是 CodeSandbox 的鏈接(可能與此處的內容略有不同,因為我在玩不同的東西): CodeSandbox
這是我最近嘗試的控制台副本:
// the last console.log from handleInputChange shows an Object with the right data
object // <= that's the typeof from handleInputChange
handleSubmit triggered
Inside handleSubmit Data: [object Object]
if() in handleSubmit triggered
Inside handleSubmit if() Data: [object Object]
Type: object Data: [object Object] // <= from useEffect
executing POST
Inside if() Type: object Data: [object Object]
Type: undefined Data: undefined // <= useEffect triggered by setSubmitted(false)
Error: "Request failed with status code 400"
日志記錄似乎表明,即使在preventDefault()
if()
和/或preventDefault()
之前,handleSubmit 函數中的inputs
狀態從普通 JavaScript 對象突變為 [object Object],但我不知道為什么。 再次是handleSubmit()
的代碼:
const handleSubmit = event => {
console.log("handleSubmit triggered")
console.log(`Inside handleSubmit Data: ${inputs}`)
if (event) {
console.log("if() in handleSubmit triggered")
console.log(`Inside handleSubmit if() Data: ${inputs}`)
event.preventDefault()
setSubmitted(true)
}
}
我可能應該強調一下,我是編程的新手,而且我不得不孤立地自學,所以我很害怕某處有明顯的錯誤。 盡管如此,我還是花了幾個小時試圖研究這個,甚至打電話給一個 React 開發人員,他也被難住了。 我已經嘗試過如何handleSubmit
,將它放在按鈕中,或者讓它由onSubmit
的箭頭函數返回。 我也試過在preventDefault
周圍移動。 似乎沒有任何幫助。
我不認為這與 Axios 有什么關系,因為在它們到達 POST 請求時inputs
已經undefined
,但是我將 Axios 作為標記放入希望這可能是面向 Axios 的程序員所熟悉的錯誤和。
同樣,通過 Postman 發出 POST 請求也很有魅力。
最后一件事:項目的后端是 .NET,所以我在 Visual Studio 上進行開發。 我認為這可能是一些有缺陷的 Visual Studio 行為,但是在 CodeSandbox 之外運行代碼會產生相同的錯誤,所以除非它是一些奇怪的格式錯誤,否則它似乎是其他東西,在我謙遜和未受過教育的觀點中。
有任何想法嗎?
這是解決問題的評論的摘要:
像下面這樣將對象傳遞到console.log()
的字符串中總是會導致顯示[object Object]
因為將其轉換為字符串,這會導致懷疑對象屬性在它們實際存在時發生了變異。
console.log(`Type: ${typeof inputs} Data: ${inputs}`);
相反,使用第二個參數或執行單獨的日志調用:
console.log(`Type: ${typeof inputs} Data:`, inputs);
之后是更正 POST 數據屬性以確保大小寫和類型與后端 API 匹配的情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.