我正在学习教程。我不明白为什么totalCounters
是null
。我在网上搜索,但我不理解。
我收到的错误消息是:
TypeError:无法读取null的属性“ counters”。
我遵循了Mosh的教程。
这是我的App.js
文件。
import React, { Component } from "react";
import NavBar from "./components/navbar";
import Counters from "./components/counters";
import "./App.css";
class App extends Component {
render() {
return (
<React.Fragment>
<NavBar totalCounters={this.state.counters.length} />
<main className="container">
<Counters
counters={this.counters}
onReset={this.handleReset}
onIncrement={this.handleIncrement}
onDelete={this.handleDelete}
/>
</main>
</React.Fragment>
);
}
}
export default App;
这是我的navbar.jsx
import React, { Component } from "react";
class NavBar extends Component {
render() {
return (
<nav className="navbar navbar-light bg-light">
<a className="navbar-brand" href="#">
Navbar <span className="badge badge-pill badge-secondary">{this.props.totalCounters}</span>
</a>
</nav>
);
}
}
export default NavBar;
这是我的counters.jsx
import React, { Component } from "react";
import Counter from "./counter";
class counters extends Component {
state = {
counters: [
{ id: 1, value: 5 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
{ id: 4, value: 0 }
]
};
handleIncrement = counter => {
const countersCopy = [...this.state.counters];
const index = countersCopy.indexOf(counter);
countersCopy[index] = { ...counter };
countersCopy[index].value++;
this.setState({ counters: countersCopy });
};
handleReset = () => {
const resetCounters = this.state.counters.map(c => {
c.value = 0;
return c;
});
this.setState({ counters: resetCounters });
};
handleDelete = counterId => {
const newCounters = this.state.counters.filter(c => c.id !== counterId);
this.setState({ counters: newCounters });
};
render() {
return (
<div>
<button
onClick={this.handleReset}
className="btn btn-primary btn-sm m2"
>
Reset
</button>
{this.state.counters.map(counter => (
<Counter
key={counter.id}
onDelete={this.props.onDelete}
onIncrement={this.handleIncrement}
counter={counter}
/>
))}
</div>
);
}
}
export default counters;
答案 0 :(得分:3)
在React中,this.state
对于每个组件都是 local 。
因此,在this.state.counters
中设置counters
不允许App
组件使用状态。
这就是counters
组件中App
为空的原因。
答案 1 :(得分:0)
因为您的App
类组件中没有状态字段。
您想在任何地方使用状态,都必须创建一个状态对象。
class App extends Component {
state = { counters: [] }
}
class App extends Component {
contructor(props) {
super(props)
this.state = { counters: [] }
}
}
答案 2 :(得分:-1)
您没有初始化状态。您的state
未定义。像这样修复它
class App extends Component {
this.state = { counters : [] }
}