如何将从 get 请求接收到的数据传递给组件?无论我尝试什么都行不通,但我的想法如下面的代码所示。谢谢!
export function data() {
axios.get('www.example.de')
.then(function(res) {
return res.data
})
.then(function(data) {
this.setState({
list: data
})
})
}
import {data} from './api.js';
class Test extends React.Component {
constructor(props) {
super(props);
this.state = {
list: ""
};
}
componentWillMount() {
data();
}
render() {
return <p > this.state.list < /p>
}
}
原文由 javascripting 发布,翻译遵循 CC BY-SA 4.0 许可协议
You call
this.setState
inside ofdata()->then
callback, sothis
is context of thethen
callback function.相反,您应该使用箭头函数(它没有自己的上下文)并将组件的this
传递给data
函数使用call
但是,您的数据服务必须不知道
setState
并且,事件更多,期望从反应组件传递this
。您的数据服务必须负责从服务器检索数据,但不负责更改组件状态,请参阅 单一职责原则。此外,可以从另一个数据服务调用您的数据服务。因此,您的数据服务应该返回承诺,组件可以使用它来调用setState
。接着