所以我有一個稱為計數器的組件,其中狀態看起來像這樣
state = {
counters: [
{ id: 1, value: 0 },
{ id: 2, value: 3 },
{ id: 3, value: 0 },
{ id: 4, value: 0 },
],
};
每次單擊相應的按鈕時,我都會嘗試增加該值。這是我為它撰寫的函式。
handleIncrement = (counter) => {
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
counters[index] = { ...counter };
counters[index].value ;
this.setState({ counters });
};
它不起作用。這里有一些額外的觀察。
- 當我 console.log 本地計數器物件(從 state.counters 復制)時,它在末尾回傳一個額外的行,id:-1 和 value:NaN
- 變數計數器(作為引數傳遞)來自子組件。如果單擊第一個按鈕,它應該回傳 0,如果單擊第二個按鈕,則回傳 1,依此類推。當我 console.log 它似乎回傳了正確的值。
從外觀上看,問題似乎在于
const index = counters.indexOf(counter);
因為 index 的值總是回傳為 -1。
uj5u.com熱心網友回復:
您可以使用索引來更新陣列中的相應記錄。
const idx = this.state.counters.findIndex((counter) => counter.id === id);
完整實施:-
import React from "react";
import "./styles.css";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
counters: [
{ id: 1, value: 0 },
{ id: 2, value: 3 },
{ id: 3, value: 0 },
{ id: 4, value: 0 }
]
};
}
handleClick = (id) => {
const idx = this.state.counters.findIndex((counter) => counter.id === id);
const counters = [...this.state.counters];
counters[idx] = { ...counters[idx], value: counters[idx].value };
this.setState(counters);
};
render() {
return (
<div>
{this.state.counters.map((counter) => (
<div>
<button onClick={() => this.handleClick(counter.id)}>
Button {counter.id}
</button>
<span>Value {counter.value}</span>
<hr />
</div>
))}
</div>
);
}
}
Codesandbox - https://codesandbox.io/s/musing-black-cippbs?file=/src/App.js
uj5u.com熱心網友回復:
試試這個來獲取索引:
const index = counters.findIndex(x => x.id === counter.id);
uj5u.com熱心網友回復:
在這里添加我的答案,以防另一個困惑的靈魂偶然發現它。
雖然看起來問題在一線之內
const index = counters.indexOf(counter);
它實際上是在呼叫函式的子組件中。在引數中,我傳遞了 counters.value,而父組件中的 handleincrement 函式期望的不是值,而是完整的物件。
其作業狀態的代碼如下父組件:
import React, { Component } from "react";
import Counter from "./counter";
class Counters extends Component {
state = {
counters: [
{ id: 1, value: 0 },
{ id: 2, value: 3 },
{ id: 3, value: 0 },
{ id: 4, value: 0 },
],
};
handleIncrement = (counter) => {
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
console.log(index);
counters[index] = { ...counter };
counters[index].value ;
this.setState({ counters });
};
子組件:
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
import React, { Component } from "react";
class Counter extends Component {
render() {
return (
<button
onClick={() => this.props.onIncrement(this.props.counter)}
className="btn btn-secondary btn-sm"
>
Increment
</button>
)
}
]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/462547.html
標籤:javascript html css 反应 网络
下一篇:如何通過單擊來切換div屬性?
