javascript - TypeError: this.setState.darkMode 在尝试实现暗模式时不是函数
问题描述
我一直在研究如何在不使用钩子的情况下实现暗模式。不幸的是,我找不到任何例子。但是,我尝试使用以下代码来实现它:
import React, { Component } from "react";
import { CountryList } from "./Components/Card-List/CountryList";
import { SearchBox } from "./Components/Search-box/Search-Box";
import "./Countries.styles.css";
class Countries extends Component {
constructor() {
super();
this.state = {
countries: [],
searchField: "",
regionField: "",
darkMode: false,
};
this.setDarkMode = this.setDarkMode.bind(this);
}
componentDidMount() {
fetch("https://restcountries.eu/rest/v2/all")
.then((response) => response.json())
.then((all) => this.setState({ countries: all, regions: all }));
}
setDarkMode(e) {
this.setState.darkMode((prevMode) => !prevMode);
}
render() {
const { countries, searchField, regionField, darkMode } = this.state;
const filterCountries = countries.filter(
(country) =>
country.name.toLowerCase().includes(searchField.toLowerCase()) &&
country.region.toLowerCase().includes(regionField.toLowerCase())
);
return (
<div className={darkMode ? "dark-mode" : "light-mode"}>
<nav>
<h1 className="header">Where in the World</h1>
<button onClick={this.setDarkMode}>Toggle Mode</button>
<h1>{darkMode ? "Dark Mode" : "Light Mode"}</h1>
</nav>
<div className="Input">
<SearchBox
type="search"
placeholder="Search a Country"
handlechange={(e) =>
this.setState({
searchField: e.target.value,
})
}
/>
<SearchBox
type="regions"
placeholder="Filter by Regions"
handlechange={(e) =>
this.setState({
regionField: e.target.value,
})
}
/>
</div>
<CountryList countries={filterCountries} />
</div>
);
}
}
export default Countries;
我得到的错误是 this.setState.darkMode 不是一个函数。不知道我错过了什么。任何帮助,将不胜感激。用钩子实现这一点似乎很简单。
解决方案
this.setState
是一个函数,我认为你试图像这样使用setState
回调:
this.setState((prevState) => ({ darkMode: !prevState.darkMode }));
推荐阅读
- java - 关于 Java 8 OptionalInt.of 参数的问题
- android - 在 Firestore 云数据库的地图视图上绘制多个标记?
- typescript - 在 TSDoc 中如何记录对象?
- mapbox - 如何按状态过滤功能
- python - 如何生成随机用户用户名并插入 django 中的数据库
- java - 如何从字符串资源文件一次设置风味版本代码和版本名称
- sql - 如何从巨大的 csv 文件中清除不良数据
- pandas - 如何在 matplotlib 的 set_xlim 中设置 'y > 0' 公式?
- python - pandas series.gt 如何使用
- java - 如何将 Python Script(py) 文件解析为 Java POJO?