这是我的index.js
代码
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";
import "bootstrap/dist/css/bootstrap.css";
import Counters from "./components/counters";
ReactDOM.render(
<React.StrictMode>
<Counters />
</React.StrictMode>,
document.getElementById("root")
);
serviceWorker.register();
Counters组件是父组件(我在index.js
中进行渲染)。
import React, { Component } from "react";
import Counter from "./counter";
class Counters extends Component {
state = {
counters: [
{ id: 1, value: 4 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
{ id: 4, value: 0 },
],
};
render() {
return (
<div>
{this.state.counters.map((counter) => (
<Counter key={counter.id} value={counter.value} selected={true} />
))}
</div>
);
}
}
export default Counters;
在上面的代码中导入的Counter组件类是:
import React, { Component } from "react";
class Counter extends Component {
state = {
count: this.props.value,
};
handleIncrement = (product) => {
console.log(product);
this.setState({ count: this.state.count + 1 });
};
render() {
console.log("props", this.props);
return (
<div>
<span className={this.getBadgeClasses()}>{this.formatCount()}</span>
<button
onClick={(product) => this.handleIncrement(product)}
className="btn btn-secondary btn-sm"
>
Increment
</button>
</div>
);
}
getBadgeClasses() {
let classes = "badge m-2 badge-";
classes += this.state.count === 0 ? "warning" : "primary";
return classes;
}
formatCount() {
const { count } = this.state;
return count === 0 ? "Zero" : count;
}
}
export default Counter;
运行此命令后,控制台日志应显示4个带有ID和值的道具。但是我一直向我展示8个道具。它将一个道具连续记录两次。你能帮我解决这个问题吗?