我正在尝试同时学习和产生一些东西。这是应该读取存储桶并生成它们列表的组件代码示例。在纸上,console.log
正在工作,但是我可以获取将列表保存到变量中的代码,该变量可用于生成XHTML
列表。
class ListBuckets extends React.Component{
constructor(props){
super(props);
this.state = {
listBuckets: []
};
this.GetBuckets = this.GetBuckets.bind(this);
}
GetBuckets(){
let tmpCmp = this;
var BucketsApi = new ForgeSDK.BucketsApi(); //Buckets Client
// Get the buckets owned by an application.
// Use the oAuth2TwoLegged client object and the credentials object that were
// obtained from the previous step
// notice that you need do add a bucket:read scope for the getBuckets to work
BucketsApi.getBuckets({}, null, tmpCmp.props.credentials)
.then(function(buckets){
console.log(buckets.body.items);
}, function(err){
console.error(err);
});
}
render(){
return (
<div className="card" style={{width: '18rem'}, {margin: "10px"}}>
<div className="card-body">
<h5 className="card-title bg-dark text-white" style={{padding: "5px"}}><FaFolder/> Buckets</h5>
<h6 className="card-subtitle">List of buckets</h6>
<p className="card-text">
This card provides a list of available buckets
</p>
{
this.props.credentials!==null
? <ul>{this.GetBuckets()}</ul>
: <div>
<div className="spinner-border spinner-border-sm"></div>
<span> Waiting for credentials...</span>
</div>
}
</div>
</div>
)
}
}
一个人可以帮我解决这个问题吗?
首先,您需要从buckets.body.items
功能存储或返回GetBuckets()
。您在这里没有对它们做任何事情,因此它们只会在函数运行后被丢弃。收到它们后,使用setState()
将它们存储在组件状态:
GetBuckets(){
let tmpCmp = this;
var BucketsApi = new ForgeSDK.BucketsApi();
BucketsApi.getBuckets({}, null, tmpCmp.props.credentials)
.then(function(buckets){
console.log(buckets.body.items);
// The important thing happens here:
this.setState({ listBuckets: buckets.body.items });
}, function(err){
console.error(err);
});
}
第二,每次重新渲染组件时都会调用此函数,因此您可能只想在组件生命周期方法之一(如componentDidMount()
)中调用它。由于它是一个异步函数,因此稍后可能需要在渲染函数中进行一些空检查。
最后,您不能只是将此数组粘贴到渲染函数中,并期望它为数组中的每个元素返回一个<li>
。您需要映射对象并返回一些JSX:
...
{
this.props.credentials!==null
? <ul>
{this.state.listBuckets.map(bucket =>
<li>bucket.data</li>)}</ul>}
: <div>
<div className="spinner-border spinner-border-sm"></div>
<span> Waiting for credentials...</span>
</div>
}
添加到@tobiasfried所说的内容:
不建议在客户端使用Forge SDK,因为它可能会暴露Forge应用程序凭据。更好的做法是提供您自己的服务器终结点,以终结点应用程序需要的任何格式进行Forge API调用并返回数据。看一下Learn Forge教程及其Node.js sample。列出所有可用存储桶的特定端点是here。