简单反应计数器

时间:2018-02-14 13:26:26

标签: javascript .net visual-studio reactjs typescript

我是学习React的新手,并选择开始使用Visual Studio的.NET + React模板,该模板在.tsx文件中提供了这段代码,作为演示如何制作一个增加a的简单按钮的示例计数器:

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();
    }
}

除非这不做任何事情 - 计数器始终保持为零。 但是代码并没有被完全跳过:在console.log(this.currentCount);内添加incrementCounter()确实显示在调试控制台中按下每个按钮时计数会增加。

那么在这里使用界面有什么特别之处?为什么增量需要通过setState而不是直接变量增量来完成?

3 个答案:

答案 0 :(得分:0)

setState用于触发一个名为shouldComponentUpdate的方法,该方法通过查看this.state中的数据来确定是否应该更新/重新呈现该组件,以查看它是否已更改。

答案 1 :(得分:0)

googleMap.setOnPoiClickListener(new GoogleMap.OnPoiClickListener() { @Override public void onPoiClick(PointOfInterest pointOfInterest) { String SS=""; isPOI=true; poiPlaceID=pointOfInterest.placeId; // Then using Google PlaceDetail API with placeId, It gives me exact Location click } }); 利用状态来存储组件所需的数据。 在开发React应用程序时,您会看到一种常见模式,其中React或部分应用程序存储在props中,因为state应该是不可变的,但{ {1}}不是。

这就是内置函数props的用武之地。有了它,你可以改变存储的数据。此外,每当您通过state更改setState()中存储的数据时,它都会触发重新呈现。

这在处理state时特别有用,例如setState()中的controlled components元素。

你应该看一下这个Tutorial,在开始学习input时帮助了我很多。

答案 2 :(得分:0)

一些事情:

当状态发生变化时,React会更新它的虚拟DOM。具体而言,它会对该更改的任何状态属性(在this.state下)做出反应。在构造函数中设置这些后,您将通过更新状态本身。 this.setState()允许React在没有性能瓶颈的情况下对实际DOM进行适当的更新。

此外,请勿像对待render()版本那样自己致电incrementCounter。这是React框架在渲染您正在处理的当前组件时使用的钩子。

要回答你的问题,interface实际上比任何事情更可选。我开发了一些React应用程序并且尚未使用它。

...至于使用setState,请参阅我上面的陈述。

相关问题