【发布时间】:2018-02-14 13:26:25
【问题描述】:
我刚开始学习 React,并选择开始使用 Visual Studio 的 .NET + React 模板,它在 .tsx 文件中给了我这段代码,作为演示如何制作一个简单的按钮来增加一个计数器:
import * as React from 'react';
import { RouteComponentProps } from 'react-router';
interface CounterState
{
currentCount: number;
}
export class Home extends React.Component<RouteComponentProps<{}>, CounterState>
{
constructor()
{
super();
this.state = { currentCount: 0 };
}
public render()
{
return <div>
<h1>Counter</h1>
<p>This is a simple example of a React component.</p>
<p>Current count: <strong>{this.state.currentCount}</strong></p>
<button onClick={() => { this.incrementCounter() }}>Increment</button>
</div>;
}
incrementCounter()
{
this.setState
({
currentCount: this.state.currentCount + 1
});
}
}
这会产生this page,它只会在按下按钮时增加数字。
我感到困惑的是为什么需要一个接口和“状态”。如果我自己实现它,它会是这样的:
import * as React from 'react';
import { RouteComponentProps } from 'react-router';
export class Home extends React.Component<RouteComponentProps<{}>>
{
currentCount: number;
constructor()
{
super();
this.currentCount = 0;
}
public render()
{
return <div>
<h1>Counter</h1>
<p>This is a simple example of a React component.</p>
<p>Current count: <strong>{this.currentCount}</strong></p>
<button onClick={() => { this.incrementCounter() }}>Increment</button>
</div>;
}
incrementCounter()
{
this.currentCount += 1;
this.render();
}
}
除了这不会做任何事情 - 计数器始终保持为零。
不过,代码并没有被完全跳过:在incrementCounter() 中添加console.log(this.currentCount); 实际上会显示在调试控制台中每按一次按钮,计数就会增加。
那么在这里使用接口有什么特别之处呢?而为什么增量需要通过setState而不是直接变量增量呢?
【问题讨论】:
-
不做
setStatereact 永远不会知道什么时候用新的状态值重新渲染你的组件。这就是为什么状态是必要的。请正确阅读官方反应文档 -
呃……React 用 typescript 看起来很糟糕
标签: javascript .net visual-studio reactjs typescript