React, Typescript, and Promises
React, Typescript, and Promises
我正在尝试编写调用web服务的组件,并通过承诺异步返回一些数据。一旦解决了这个问题,我想在我的组件的渲染方法中包含结果。理想情况下,我想我希望的承诺被传递到另一个组件的结果。即;承诺的结果是一个项目列表。
还有一件事-我正在使用Typescript编写这个React组件。
目前我有以下代码:
componentWillMount() {
let fooProps = listGetter.returnListData().then((response) => {
return response;
});
}
public render(): JSX.Element {
<div>
<Foo ElementProperties={this.fooProps} />
</div>
}
然而,这段代码出错并显示"cannot assign null value to property"。
我做错了什么?什么是最好的方式来处理承诺和解决他们成组件在REACT?
谢谢!
你应该使用组件的状态。
改变状态会导致组件的重新呈现,就像组件改变子组件的属性会导致子组件被重新呈现一样。
类似:
componentWillMount() {
listGetter.returnListData().then((response) => {
this.setState({
fooProps: response.fooProps
});
});
}
public render(): JSX.Element {
<div>
<Foo ElementProperties={ this.state.fooProps } />
</div>
}
promise永远不会返回它们的值,它们只返回一个Thenable
,所以你可以链接它们。您正在寻找的返回值将在传递给then
的函数的第一个参数中
componentWillMount() {
// bind the function to `this` so even if you don't use an
// anonymous arrow function this call will work in the right context
let updateComponent = this.updateComponent.bind(this);
listGetter.returnListData().then((res) => {
updateComponent(res);
})
}
updateComponent(res) {
this.setState({fooProps: res.fooProps})
}
相关文章:
- 可以简化嵌套的延迟Q Promises解析吗
- Selenium WebDriver and JavaScript change
- PHP and Javascript functions
- Javascript Return and if/else
- SetTimeout and clearTimeout in Javascript
- lightbox in html 5 and javascript
- TimelineJS and AngularJS
- timeago.js with datatable and PHP
- javascript button ajax and php
- Ajax and Json with Rails
- Combine onload, onresize and onclick
- php布尔值's小写AND大写和数字布尔值'可以接受
- setTimeout and V8
- Jquery post and onclick
- Moment js and IOS
- Rails 3.2 and Paloma gem
- JavaScript Promises and setTimeout
- Javascript, Node, Promises, and recursion
- Angularjs and Requirejs promises
- React, Typescript, and Promises