我的问题是,当我删除动态添加的输入时,它会删除错误的输入。我在jsfiddle https://jsfiddle.net/armakarma/qwg3j2fa/24/中复制了代码。尝试添加更多五个输入,在每个输入中键入内容,然后尝试删除第二个输入。它将删除最后一个。我在哪里做错了?
addNewInputs() {
let newInputValues = {
datetime: "10.05.2019 14:00",
position_id: 1,
contact: "",
address_id: "",
new_address: "",
}
this.setState(prevState => ({
arrayOfAddresses: [...prevState.arrayOfAddresses, newInputValues],
}))
}
deleteInput(idx) {
let tempObj = this.state.arrayOfAddresses
tempObj.splice(idx, 1)
this.setState(prevState => ({
arrayOfAddresses: tempObj,
}))
}
onChooseAddress(e, idx) {
console.log(e.target.value)
}
render() {
return ( <
div > {
this.state.arrayOfAddresses.map((item, idx) => {
return (
<div key = {idx} >
<input name = "contact"
onChange = {(e) => this.onChooseAddress(e)}
/>
<button onClick = {() => this.deleteInput(idx)} > x < /button>
</div>
)
})
}
<button onClick = {() => this.addNewInputs()} > Add new input < /button>
/div>
)
}
}
答案 0 :(得分:1)
问题出在chooseAddress
方法上,您没有从onChange
回调传递索引,这就是状态未更新的原因,并且您还没有添加value
支撑输入,这就是渲染错误的原因,因为输入的内部状态
class TodoApp extends React.Component {
constructor(props) {
super(props)
this.state = {
adresses:[
{
"id": 1,
"address": "address 1",
},
{
"id": 2,
"address": "address 2",
},
{
"id": 3,
"address": "address 3",
},
{
"id": 4,
"address": "address 4",
}
],
arrayOfAddresses: [
{
datetime: "10.05.2019 14:00",
position_id: 1,
contact: "",
address_id: "",
new_address: "",
},
],
}
}
addNewInputs() {
let newInputValues = {
datetime: "10.05.2019 14:00",
position_id: 1,
contact: "",
address_id: "",
new_address:"",
}
this.setState(prevState => ({
arrayOfAddresses: [...prevState.arrayOfAddresses, newInputValues],
}))
}
deleteInput(idx) {
this.setState(prevState => {
let tempObj = [...prevState.arrayOfAddresses]
tempObj.splice(idx, 1)
console.log(tempObj)
return {
arrayOfAddresses: tempObj,
}
})
}
onChooseAddress(e, idx) {
const {value} = e.target;
this.setState(state=>{
let tempObj = [...this.state.arrayOfAddresses]
tempObj[idx].new_address = value
return {
arrayOfAddresses: tempObj,
}
})
}
render() {
return (
<div>
{this.state.arrayOfAddresses.map((item,idx)=>
<div>
<input
name="contact"
value={item.new_address}
onChange={(e) => this.onChooseAddress(e, idx)}
/>
<button onClick={() => this.deleteInput(idx)}> x</button>
</div>
)}
<button onClick={() => this.addNewInputs()}> Add new input </button>
</div>
)
}
}
ReactDOM.render(<TodoApp />, document.querySelector("#app"))
答案 1 :(得分:1)
您需要更改两件事:
设置value
中的<input>
。问题是arrayOfAddresses
的设置正确,但正确的值未反映在输入中。
将相应的idx
值添加到onChange
的{{1}}
这是相关的代码更改:
<input>
这是小提琴: JSFiddle
答案 2 :(得分:-1)
您不应按索引删除项目。您应按项目ID删除,使用lodash的filter
函数:https://lodash.com/
deleteInput(id) {
let tempObj = [...this.state.arrayOfAddresses]
tempObj = _.filter(tempObj, obj => obj.id != id)
this.setState(prevState => ({
arrayOfAddresses: tempObj,
}))
}
...
<button onClick = {() => this.deleteInput(item.id)} > x < /button>