首页 > 解决方案 > 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 不是一个函数。不知道我错过了什么。任何帮助,将不胜感激。用钩子实现这一点似乎很简单。

标签: javascriptreactjs

解决方案


this.setState是一个函数,我认为你试图像这样使用setState回调

this.setState((prevState) => ({ darkMode: !prevState.darkMode }));

推荐阅读