React Hooks-使用 useState 对抗仅仅变量

React Hooks 提供了 useState 选项,我经常看到 Hooks 与 Class-State 的比较。那钩子和一些常规变量呢?

比如说,

function Foo() {
let a = 0;
a = 1;
return <div>{a}</div>;
}

我没有使用 Hooks,它会给我同样的结果:

function Foo() {
const [a, setA] = useState(0);
if (a != 1) setA(1); // to avoid infinite-loop
return <div>{a}</div>;
}

那么这有什么区别呢? 在这种情况下使用 Hooks 更加复杂... ... 那么为什么要开始使用它呢?

44547 次浏览

The reason is if you useState it rerenders the view. Variables by themselves only change bits in memory and the state of your app can get out of sync with the view.

Compare this examples:

function Foo() {
const [a, setA] = useState(0);
return <div onClick={() => setA(a + 1)}>{a}</div>;
}


function Foo() {
let a = 0;
return <div onClick={() => a + 1}>{a}</div>;
}

In both cases a changes on click but only when you use useState the view correctly shows a's current value.

Your first example only works because the data essentially never changes. The enter point of using setState is to rerender your entire component when the state hanges. So if your example required some sort of state change or management you will quickly realize change values will be necessary and to do update the view with the variable value, you will need the state and rerendering.

Updating state will make the component to re-render again, but local values are not.

In your case, you rendered that value in your component. That means, when the value is changed, the component should be re-rendered to show the updated value.

So it will be better to use useState than normal local value.

function Foo() {
let a = 0;
a = 1; // there will be no re-render.
return <div>{a}</div>;
}


function Foo() {
const [a, setA] = useState(0);
if (a != 1) setA(1); // re-render required
return <div>{a}</div>;
}
function Foo() {
const [a, setA] = useState(0);
if (a != 1) setA(1); // to avoid infinite-loop
return <div>{a}</div>;
}

is equivalent to

class Foo extends React.Component {
constructor(props) {
super(props);
this.state = {
a: 0
};
}
// ...
}

What useState returns are two things:

  1. new state variable
  2. setter for that variable

if you call setA(1) you would call this.setState({ a: 1 }) and trigger a re-render.

Local variables will get reset every render upon mutation whereas state will update:

function App() {
let a = 0; // reset to 0 on render/re-render
const [b, setB] = useState(0);


return (
<div className="App">
<div>
{a}
<button onClick={() => a++}>local variable a++</button>
</div>
<div>
{b}
<button onClick={() => setB(prevB => prevB + 1)}>
state variable b++
</button>
</div>
</div>
);
}

Edit serene-galileo-ml3f0