如何在 React 中使用函数 return 值作为状态?

How to use function return value as a state in React?

我正在使用 React 学习功能组件,我有一个简单的代码,当状态值为 0 时 returns 'Nah'。

问题是这在渲染期间不起作用。这是为什么?

import React, { useState } from "react";
import { Button } from "react-bootstrap";
const Counter = () => {
  const [count, setCount] = useState(0);
  const formatCount = () => {
    count === 0 ? setCount("Nah") : setCount(0);
  };

  // let classes = "badge m-2";
  // classes += (this.state.count === 0) ? "badge-warning" : "badge-primary";

  return (
    <div>
      <Button className="badge badge-warning m-2">-</Button>
      {this.formatCount()}
      <button>+</button>
    </div>
  );
};

export default Counter;

我认为你的代码应该处理数字而不是字符串。

问题,

1:

{this.formatCount()}

您在功能组件中而不是 class,因此不需要 this

2:(主要)

count === 0 ? setCount("Nah") : setCount(0);

它有递归,
首先 count0 触发 setCount("Nah")
然后,在第二个渲染中,count 不是 0 触发 setCount(0)

这个循环破坏了应用程序


修复

使用这样的东西,

const formatCount = () => {
    return count === 0 ? 'Nah' : count
}

您的代码中有几处可以用不同的方式完成。

首先,您的函数 formatCount() 没有 return 值。所以执行时几乎没有什么可显示的。

其次,你的函数是在状态更新值之前执行的,导致它一直停留在0.

更好的方法是:

import React, { useState, useEffect } from "react";
import { Button } from "react-bootstrap";
const Counter = () => {
  const [count, setCount] = useState(0);

  useEffect(() => {
      formatCount();
  }, []);

  const formatCount = () => {
    count === 0 ? setCount("Nah") : setCount(0);
  };

  // let classes = "badge m-2";
  // classes += (this.state.count === 0) ? "badge-warning" : "badge-primary";

  return (
    <div>
      <Button className="badge badge-warning m-2">-</Button>
      {count}
      <button>+</button>
    </div>
  );
};

export default Counter;

这会导致 count 在渲染时更新并在更改时自动重新渲染到屏幕。

可以找到有关 useEffect() 挂钩的更多信息 here