根据条件使用 json 填充选择器

fill a picker usin json according to a condition

我可以使用 json 库存状态

来填充选择器
  produits: [{
      "code": 11,
      "pu": 50,
      "ps": 50,
      "des": "P 1",
      "promo": "1",
    }, {
      "code": 22,
      "pu": 100,
      "ps": 100,
      "des": "P 2",
      "promo": "1",
    }, {
      "code": 33,
      "pu": 80,
      "ps": 80,
      "des": "P 3",
      "promo": "0",
    },
    {
      "code": 44,
      "pu": 120,
      "ps": 120,
      "des": "P 4",
      "promo": "1",
    },
  ],

我想要的是同一件事,但如果 produits.promo === '1' 将显示此项目,否则将不会显示,这是我的方法,但它有一个空的选择器:当我单击没有任何变化:

          {<Picker
            style={Styles.picker}
            selectedValue={this.state.pu}
            onValueChange={(itemValue, itemIndex) => this.setState({pu: itemValue, codeProduit: itemIndex+1,})} >
            { this.state.produits.map((item, key)=>
              {if (item.promo === "0") {
                <Picker.Item label={item.des} value={item.pu} key={item.code} />
                }
              }
            )}
          </Picker>}

PS。它在没有 If 块的情况下运行良好:

<Picker.Item label={item.des} value={item.pu} key={item.code} />

我的方法有什么问题?

我不确定我是否理解正确,但我会试一试。有关解释,请参阅代码注释。

渲染方法

 render() {
    return (
      <View style={styles.container}>
        <Picker
            selectedValue={this.state.pu}
            onValueChange={(itemValue, itemIndex) => this.setState({pu: itemValue, codeProduit: itemIndex+1,})} >
            {this.renderPicker()}            
          </Picker>
      </View>
    );
  }

renderPicker 方法:

  renderPicker(){
    const items = this.state.produits.map((item, key)=> {
      // if item.promo === "1" return picker item 
      if (item.promo === "1") {
      // make sure to return Picker Item
      return (<Picker.Item label={item.des} value={item.pu} key={item.code} />);
      }
    });
    // return list of pickers
    return items; 
  }

输出:

工作示例:

https://snack.expo.io/@tim1717/trembling-turkish-delight

只需使用过滤器创建一个新的产品数组

render() {
const promoProduits = this.state.produits.filter(item => item.promo === '1');
....

然后像这样渲染

{<Picker
    style={Styles.picker}
    selectedValue={this.state.pu}
    onValueChange={(itemValue, itemIndex) => this.setState({pu: itemValue, codeProduit: itemIndex+1,})} >
    {
     promoProduits.map((item, key)=> (<Picker.Item label={item.des} value={item.pu} key={item.code} />)
    }
</Picker>}