TypeError:尝试实现暗模式时,this.setState.darkMode不是函数

时间:2020-04-09 16:54:18

标签: javascript reactjs

我一直在研究如何在不使用钩子的情况下实现暗模式。不幸的是,我找不到任何例子。但是,我尝试使用以下代码来实现它:

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不是一个函数。不知道我在想什么。任何帮助,将不胜感激。用钩子实现这一目标似乎很简单。

2 个答案:

答案 0 :(得分:3)

this.setState是一个函数,我想您正试图像这样使用setState with callback

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

答案 1 :(得分:0)

this.setState是一个用于在react中更新类组件的state属性的函数。因此,您无法使用this.setState.darkMode访问darkMode属性。如果您想读取darkMode属性,则必须使用:

let isDarkMode = this.state.darkMode

如果要设置darkMode属性,则必须使用:

this.setState({darkMode: true})

现在,如果要反转darkMode属性,则应使用:

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