小编Hug*_*sen的帖子

与打字稿反应 - 使用 setState 进行类型安全

所以我最近发现事件处理程序的回调对渲染性能不利:https : //reactjs.org/docs/handling-events.html

我试图通过在类方法中从事件中获取属性而不是执行以下操作来注意这一点:onClick={({value}) => this.setState({"someProperty" as keyof State: value})}等。

但是,现在我无法在该回调中显式声明类型安全性,我正在尝试对其进行动态处理,并且我的类型检查器对下面的代码没问题,但是我如何让它抱怨输入元素的name属性不是一个keyof State

interface State {
  someProperty: string;
}

class MakeMeSafer extends React.Component<{}, State> {

  state: State = {
    someProperty: ''
  }

  set = ({ currentTarget: { name, value } }: React.SyntheticEvent<HTMLInputElement>): void => {
    this.setState({ [name as keyof State]: value });
  }

  render(): JSX.Element {
    return (
      <div>
        <input type="text" name="some-name-not-in-state" onChange={this.set} />
      </div>
    );
  }

}
Run Code Online (Sandbox Code Playgroud)

javascript setstate typescript typesafe reactjs

5
推荐指数
1
解决办法
7849
查看次数

我的提取请求被取消,我不知道为什么

我正在创建一个使用https://restcountries.eu/ API的网络应用程序。

当用户输入国家/地区时,我将使用fetch. 但是,我的请求总是被取消。

我测试了捕获用户输入的部分,但我认为问题出在我的fetch代码上。

var countryName; // This will receive the user input on a textbox in my HTML file.
var resultado;

function grabCountry(urlendpoint, countryName, endpointfields) {

  countryName = document.getElementById('searchInput').value;

  var urlendpoint = 'https://restcountries.eu/rest/v2/name/';    
  var endpointfields = '?fields=topLevelDomain;alpha3Code;callingCodes;altSpellings;subregion;population;latlng;languages;flag';

fetch(urlendpoint + countryName + endpointfields)
 .then(response => data)
 .then(data => {
   console.log(data())
})
}
Run Code Online (Sandbox Code Playgroud)

IMAGE:我总是在网络中收到此错误

IMAGE:控制台中的这个错误

javascript fetch

5
推荐指数
2
解决办法
303
查看次数

标签 统计

javascript ×2

fetch ×1

reactjs ×1

setstate ×1

typesafe ×1

typescript ×1