我有一段调用 Web 服务的代码,但我有一些问题。
第一个是,调用第二个 WS 的最佳实践是什么,现在我只调用一个并在列表中显示数据,但是如果我有第二个 WS,我应该在 componentDidMout() 方法中调用它吗? ?
现在我有一个名为 data 的数组,但是例如,我应该使用第二个数组进行第二个 WS 调用吗?
第二个问题是,如何在 Material ui 下拉列表中填充 WS 的结果,我想用 WS 附带的数据填充它们。
我是新手,所以一些帮助会很好。
import React, { Component } from 'react';
import DropDownMenu from 'material-ui/DropDownMenu';
export default class WebserviceTest extends Component {
constructor() {
super();
this.state = {
data: []
};
}
componentDidMount() {
const url = 'https://randomuser.me/api/?results=4';
fetch(url).
then((Response) => Response.json()).
then((findResponse) => {
console.log(findResponse);
this.setState({
data: findResponse.results
});
});
}
render() {
const listDesc = this.state.data.map((dt, i) =>
<div>
<div>
<li key={i}>{dt.name.first}</li>
</div>
</div>
);
return (
<div>
<ul>{listDesc}</ul>
</div>
);
}
}
上面的代码工作正常。
感谢和问候。
最佳答案
关于用数据填充下拉列表,这应该可以完成工作。尚未测试代码。与 material-ui/Dropdown
相关的所有内容都可以 check here .
import React, { Component } from "react";
import DropDownMenu from "material-ui/DropDownMenu";
import MenuItem from "material-ui/MenuItem";
export default class WebserviceTest extends Component {
constructor() {
super();
this.state = {
data: []
};
this.renderOptions = this.renderOptions.bind(this);
}
componentDidMount() {
const url = "https://randomuser.me/api/?results=4";
fetch(url)
.then(Response => Response.json())
.then(findResponse => {
console.log(findResponse);
this.setState({
data: findResponse.results
});
});
}
//will set wahtever item the user selects in the dropdown
handleChange = (event, index, value) => this.setState({ value });
//we are creating the options to be displayed
renderOptions() {
return this.state.data.map((dt, i) => {
return (
<div>
<MenuItem key={i} value={dt.name.first} primaryText={dt.name.first} />
</div>
);
});
}
render() {
return (
<div>
<DropDownMenu value={this.state.value} onChange={this.handleChange}>
{this.renderOptions()}
</DropDownMenu>
</div>
);
}
}
What is the best practice to call a second Web Service??
回答:在 componentDidMount
中调用是可以的。此外,它还取决于其他因素。如果两个 WS 调用是独立的,那么您可以使用 Promise 并行调用它们,例如:
Promise
.all([
fetch('https://randomuser.me/api/?results=4').then((res) => res.json()),
fetch('https://randomuser.me/api/?results=4').then((res) => res.json()),
])
.then((response) => console.log(response)
)
提示:如果您将上面的代码片段粘贴到控制台中,您将获得输出。您可以检查输出。它返回一个响应数组。
now I have an array called data but the for example, should I use a second array for a second WS call?
这取决于您想要对第二个 WS 的数据执行什么操作。如果您想添加到下拉列表中,那么您可以简单地与 data
数组连接。如果想要用于除您之外的其他目的应将数据分开。
And the second one is, how can I populate the result of the WS in a material ui dropdown, I want to populate them with the data coming with the WS.
粘贴在开头的代码应该可以工作。您可以简单地映射要在列表中显示的数据创建选项
关于javascript - 使用 React js 调用两个以上的 Web 服务并将它们填充到 Material ui 下拉列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47323014/