簡體   English   中英

如何使用流星將一組對象從集合中返回到狀態?

[英]How to return an array of objects from a collection, to state in react using meteor?

我正在使用react-select來收集已經在名為tags的mongodb集合中定義的tags ,我需要在數組options[] ins中插入我的標簽,就像在staticOptions[]

issue: handleOptions() console.log(name)僅記錄for循環中的第一個項目。

問題:如何將一組對象從tags集合返回到this.state.options ,就像staticOptions

//-------create class: Addgifts-----
export default class Addgifts extends Component{
constructor(){
super()
this.state={
  value: [],
  options: [],
  staticOptions: [{ label: 'Chocolate', value: 'chocolate' },
            { label: 'Vanilla', value: 'vanilla' },
            { label: 'Strawberry', value: 'strawberry' },
          ]
 }
}

//-------Handle options--------
handleOptions(){
let KeyWords = this.props.tags;
for (i=0 ; i<KeyWords.length ; i++){
  return KeyWords[i].map.name((names)=>{
    console.log(name);
    return(
       this.state.options.push({label:{name},value:{name}});
      )
    }
  });
 }
}

//-----Select Change----
handleSelectChange (value) {
    console.log('You\'ve selected:', value);
this.setState({
    value
 });
}

//-----Select package----
<div>
 <Select
 multi={true}
 value={this.state.value}
 placeholder="Select all KeyWord(s)"
 options={this.handleOptions()}
 onChange={this.handleSelectChange.bind(this)} />
</div>

//-----subscribing tags from mongodb----
Addgifts.propTypes={tags: PropTypes.array.isRequired,};
export default createContainer(()=>{
Meteor.subscribe('tags');
return {gifts: Gifts.find({},{sort:{name:-1}}).fetch(),};
},Addgifts);

首先,您應該將props中的數據傳輸到componentDidMount()或(componentWillReceiveProps()中的狀態,如果使用新的道具更新道具)並直接將選項傳遞給選擇框。 在handleOptions()中執行它不是一個好主意。

其次,我相信handleOptions中的邏輯對於迭代對象數組是不正確的。

做這樣的事情。

componentDidMount: function() {
  var options = [];
  for (i=0 ; i<this.props.tags.length ; i++){
    var name = this.props.tags[i].name;
    console.log(name);
    options.push({label:name, value: name});
  }
  this.setState({options: options});
},

render: function() {
  return (
    <div>
      <Select
      multi={true}
      value={this.state.value}
      placeholder="Select all KeyWord(s)"
      options={this.state.options}
      onChange={this.handleSelectChange.bind(this)} />
    </div>
  );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM