[英]this.state is NULL in ReactJs component
我正在學習教程。 我不明白為什么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;
在React中, this.state
對於每個組件都是本地的 。
因此,在counters
中設置this.state.counters
不允許App
組件使用狀態。
這就是為什么counters
在App
組件中為null的原因。
因為您的App
類組件中沒有狀態字段。 您想在任何地方使用狀態,都必須創建一個狀態對象。
class App extends Component {
state = { counters: [] }
}
class App extends Component {
contructor(props) {
super(props)
this.state = { counters: [] }
}
}
您沒有初始化狀態。 您的state
未定義。 像這樣修復它
class App extends Component {
this.state = { counters : [] }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.