开发者问题收集

在 React 类组件问题中构建递归方法

2022-11-08
37

我正在尝试制作一个递归类组件来检查输入是否为回文。 但是当我尝试调用此函数内部的回文函数时,它会开始无限期地调用。使用 vanilla js,此方法工作正常。我在这里做错了什么?以及当输入字段为空时如何更改输出。

import React, { Component } from "react";

import "./App.css";

export default class App extends Component {
  state = { data: "", palindrome: "" };

  inputHandeler = (e) => {
    this.setState({ data: e.target.value });
  };
  palindrome = () => {
    if (this.state.data.length === 1 || this.state.data.length === 0) {
      this.setState({ palindrome: "this is palindrome" });
    } else if (
      // input abba console.log("indefinitely ")
      this.state.data[0] === this.state.data[this.state.data.length - 1]
    ) {
      this.palindrome(this.state.data.slice(1, this.state.data.length - 1));
    } else {
      this.setState({ palindrome: "this is not palindrome" });
    }
  };

  render() {
    return (
      <div className="container">
        <h1> Palindrome Checking App</h1>
        <div className="app">
          <div className="inputfield">
            <label name=" palindrome ">
              Input text to check if it is a palindrome:
            </label>
            <input id="palindrome " type="text" onChange={this.inputHandeler} />
            <button onClick={this.palindrome}>Check</button>
          </div>
          <div className="output">{this.state.palindrome}</div>
        </div>
      </div>
    );
  }
}
1个回答

您需要定义回文方法以不依赖于当前状态。

palindrome = (data: string[]) => {
  if (data.length === 1 || data.length === 0) {
    this.setState({ palindrome: "this is palindrome" });
  } else if (
    // input abba console.log("indefinitely ")
    data[0] === data[data.length - 1]
  ) {
    this.palindrome(data.slice(1, data.length - 1));
  } else {
    this.setState({ palindrome: "this is not palindrome" });
  }
};

render() {
  return (
    ...
    <button onClick={() => this.palindrome(this.state.data)}>Check</button>
    ...
  );
}
smac89
2022-11-08