使用Material-UI

时间:2019-04-30 14:57:13

标签: reactjs api filter axios material-ui

我正在尝试使用Axios和ReactJS过滤响应数据。

我已经为他们的selection controls使用了Material-UI来切换过滤器。

使用事件处理程序将不同的数据传递到Axios并重新加载当前数据。

我正在尝试使用多种过滤器,例如:

过滤器选项A,B和C

切换过滤器选项A:显示过滤器A

在切换过滤器A仍为true的情况下,我点击了切换过滤器B:显示过滤器A&B

我希望我解释得足够好。我希望能够同时过滤多个参数。

我的代码有点草率,因为这对我来说是很新的。当我创建了两次相同的函数时,理想情况下,我将能够通过一个函数过滤多个值,并通过选定的触发器获取参数,但是我首先想使过滤工作。

我已经尝试了当前代码的多种变体。尝试更改filter1或filter2的过滤器值

构造函数,数据装入,事件处理程序

    super(props);
    const { classes } = props;
    const { products, images } = this.props;
    const filteredproducts = '' ;
    this.state = {
      productsData: {},
      isLoading: true,
      error: null,
      products,
      images,
      classes,
      filteredproducts : products,
      expanded: null,
      gilad: false,
      jason: false,
      include: '?include=images',
      url: 'https://stern-telecom-react-salman15.c9users.io/api/v2/storefront/products',
      filter1: '',
      filter2: '',

    };
  }

  componentDidMount() {

    this.setState({ isLoading: true });
    axios.get(this.state.url + this.state.include)
      .then(result => this.setState({
        productsData: result.data,
        filteredproducts: result.data.data,
        images: result.data.included,
        isLoading: false,
      }))
      .catch(error => this.setState({
        error,
        isLoading: false
      }));
    if ( this.state.isloading == false) {
      nouislider.create(this.refs.slider2, {
        start: [0, 100],
        connect: [false, true, false],
        step: 1,
          range: { 
            min: 0, 
            max: 100 
          }
      });
    }
  }


  handleChange = panel => (event, expanded) => {
    this.setState({
      expanded: expanded ? panel : false,
    });
  };

  handleFormChange1 = name => event => {

    if( event.target.checked != true ) {

    this.setState({ 
      isLoading: true, 
      [name]: '',
       filter1: 'filter[taxons]=1',
    });
    axios.get( this.state.url + this.state.include + '&'+ this.state.filter1 + '&'+ this.state.filter2)
      .then(result => this.setState({
        productsData: result.data,
        filteredproducts: result.data.data,
        images: result.data.included,
        isLoading: false,
      }))
      .catch(error => this.setState({
        error,
        isLoading: false
      }));
       console.log('true',event.target.checked, this.state.url + this.state.include + '&'+ this.state.filter1 + '&'+ this.state.filter2)
    }
    else {
      this.setState({ 
        isLoading: true, 
        [name]: event.target.checked,
       filter1: '',

      });
      axios.get(this.state.url + this.state.include + '&'+ this.state.filter1 + '&'+ this.state.filter2)
        .then(result => this.setState({
          productsData: result.data,
          filteredproducts: result.data.data,
          images: result.data.included,
          isLoading: false,
        }))
        .catch(error => this.setState({
          error,
          isLoading: false
        }));
        console.log('false', event.target.checked, this.state.url + this.state.include + '&'+ this.state.filter1 + '&'+ this.state.filter2)
    }
  };


handleFormChange2 = name => event => {
    if( event.target.checked != true ) {
    this.setState({ 
      isLoading: true, 
      [name]: '',
      filter2: 'filter[taxons]=3',
    });


    axios.get(this.state.url + this.state.include + '&'+ this.state.filter1 + '&'+ this.state.filter2)
      .then(result => this.setState({
        productsData: result.data,
        filteredproducts: result.data.data,
        images: result.data.included,
        isLoading: false,
      }))
      .catch(error => this.setState({
        error,
        isLoading: false
      }));
       console.log('true',[name],event.target.checked, this.state.API2 )
    }
    else {
      this.setState({ 
        isLoading: true, 
        [name]: event.target.checked,
        filter2: '',
      });

      axios.get(this.state.url + this.state.include + '&'+ this.state.filter1 + '&'+ this.state.filter2)
        .then(result => this.setState({
          productsData: result.data,
          filteredproducts: result.data.data,
          images: result.data.included,
          isLoading: false,
        }))
        .catch(error => this.setState({
          error,
          isLoading: false
        }));
        console.log('false', [name], event.target.checked, this.state.API2)
    }
    console.log(event.target.checked)
  };  

用户互动


              <ExpansionPanel defaultExpanded={true}>
                <ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}>
                  <Typography className={this.state.classes.heading}>Model</Typography>
                  <Typography className={this.state.classes.secondaryHeading}>Redmi, Go, Mi, Pro</Typography>
                </ExpansionPanelSummary>
                <ExpansionPanelDetails>
                 <FormControl component="fieldset">
                  <FormLabel component="legend">Assign responsibility</FormLabel>
                  <FormGroup>
                    <FormControlLabel
                      control={
                        <Switch
                          checked={this.state.gilad}
                          onChange={this.handleFormChange1('gilad')}
                          value="gilad"
                        />
                      }
                      label="Mi"
                    />
                    <FormControlLabel
                      control={
                        <Switch
                          checked={this.state.jason}
                          onChange={this.handleFormChange2('jason')}
                          value="jason"
                        />
                      }
                      label="Redmi"
                    />
                    <FormControlLabel
                      control={
                        <Switch
                          checked={this.state.antoine}
                          onChange={this.handleFormChange3('antoine')}
                          value="antoine"
                        />
                      }
                      label="Go"
                    />
                  </FormGroup>
                  <FormHelperText>Be careful</FormHelperText>
                </FormControl>
                </ExpansionPanelDetails>
              </ExpansionPanel>

我期望的是,当我切换多个过滤器选项时,我得到的数据Feed实际上显示了过滤后的数据(过滤器选项A和过滤器选项B)

例如,当我执行handleFormChange1时,我将filter1的状态设置为=taxon

当我执行handleFormChange2时,filter2的状态为另一个分类单元

现在发生的是,如果我给filter1一个值,然后切换filter2,则filter1的值将再次清空。

更新!可以工作的过滤器...

我已经设法简化了代码并能够切换过滤器,但是仍然存在问题。我的意思是,在更改生效之前,我必须两次按下切换开关。

如下面的代码所示,执行handleFormChange函数时,如果将其各自的切换设置为true

,它会更改过滤器的状态。

但是,当我第一次按下切换键时,发生的是我的产品列表在更改相应的过滤器之前得到更新。因此,在加载更改之前,我必须再次按下相同的切换开关。

我希望按一下切换按钮,然后更改过滤器值,然后刷新productslist

在过滤器值更改被传递之前,我必须多次按下切换按钮。

  handleFormChange = name => event => {
    //Change filter's value when the button's value has changed to true or false
    this.setState({ 
      isLoading: true, 
      [name]: event.target.checked,
      filter1: this.state.mi === true ? "1," : '',
      filter2: this.state.redmi === true ? "3," : '',
      filter3: this.state.go === true ? "4,": '',

    });
    //Check if the filter is changed
    console.log('filtersSet', this.state.filter1, this.state.filter2, this.state.filter3)
    //Get new data request from API with new filter value's
      axios.get(this.state.url + this.state.include + '&'+ this.state.taxons + this.state.filter1 + this.state.filter2+ this.state.filter3 + this.state.filter4 + this.state.filter5 + this.state.filter6)
        .then(result => this.setState({
          productsData: result.data,
          filteredproducts: result.data.data,
          images: result.data.included,
          isLoading: false,
        }))
        .catch(error => this.setState({
          error,
          isLoading: false
        }));
        //check the value passed on, the value of the event target and if the state has been changed. 
       console.log(name,event.target.checked, this.state.filter1 , this.state.filter2, this.state.filter3, this.state.mi , this.state.redmi, this.state.go)
  };
<React.Fragment>
        <div className={this.state.classes.root}>
          <GridContainer>
            <GridItem xs={12} sm={12} md={3} className={this.state.classes.marginAuto}>
              <ExpansionPanel defaultExpanded={true}>
                  <ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}>
                    <Typography className={this.state.classes.heading}>Model</Typography>
                    <Typography className={this.state.classes.secondaryHeading}>Redmi, Go, Mi, Pro</Typography>
                  </ExpansionPanelSummary>
                  <ExpansionPanelDetails>
                   <FormControl component="fieldset">
                    <FormLabel component="legend">Assign responsibility</FormLabel>
                    <FormGroup>
                      <FormControlLabel
                        control={
                          <Switch
                            checked={this.state.mi}
                            onChange={this.handleFormChange('mi')}
                            value="1,"
                          />
                        }
                        label="Mi"
                      />
                      <FormControlLabel
                        control={
                          <Switch
                            checked={this.state.redmi}
                            onChange={this.handleFormChange('redmi')}
                            value="3,"
                          />
                        }
                        label="Redmi"
                      />
                      <FormControlLabel
                        control={
                          <Switch
                            checked={this.state.go}
                            onChange={this.handleFormChange('go')}
                            value="4,"
                          />
                        }
                        label="Go"
                      />
                    </FormGroup>
                    <FormHelperText>Be careful</FormHelperText>
                  </FormControl>
                  </ExpansionPanelDetails>
                </ExpansionPanel>

                <ExpansionPanel defaultExpanded={true}>
                  <ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}>
                    <Typography className={this.state.classes.heading}>Advanced settings</Typography>
                    <Typography className={this.state.classes.secondaryHeading}>
                      Filtering has been entirely disabled for whole web server
                    </Typography>
                  </ExpansionPanelSummary>
                  <ExpansionPanelDetails>
                    <div className={this.state.classes.sliderContainer}>
                      <div className="slider-info noUi-active" ref="slider2"  />
                    </div>
                  </ExpansionPanelDetails>
                </ExpansionPanel>

                <ExpansionPanel defaultExpanded={true}>
                  <ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}>
                    <Typography className={this.state.classes.heading}>Users</Typography>
                    <Typography className={this.state.classes.secondaryHeading}>
                      You are currently not an owner
                    </Typography>
                  </ExpansionPanelSummary>
                  <ExpansionPanelDetails>
                     <FormControl component="fieldset">
                    <FormLabel component="legend">Assign responsibility</FormLabel>
                    <FormGroup>
                      <FormControlLabel
                        control={
                          <Switch
                            checked={this.state.gilad1}
                            onChange={this.handleFormChange('gilad1')}
                            value="gilad"
                          />
                        }
                        label="32GB"
                      />
                      <FormControlLabel
                        control={
                          <Switch
                            checked={this.state.jason1}
                            onChange={this.handleFormChange('jason1')}
                            value="jason"
                          />
                        }
                        label="64GB"
                      />
                      <FormControlLabel
                        control={
                          <Switch
                            checked={this.state.antoine1}
                            onChange={this.handleFormChange('antoine1')}
                            value="antoine"
                          />
                        }
                        label="126GB"
                      />
                    </FormGroup>
                    <FormHelperText>Be careful</FormHelperText>
                  </FormControl>
                  </ExpansionPanelDetails>
                </ExpansionPanel>
            </GridItem>
          {
             (error) ? (
                <GridItem xs={12} sm={12} md={9} className={this.state.classes.productContainer}> 
                  <p>{error.message}</p>
                </GridItem> 
            ): (isLoading) ?  (
                  <GridItem xs={12} sm={12} md={9} className={this.state.classes.productContainer}> 
                      <Loading/>
                  </GridItem>
            ): (isLoading) == false ? (
              <GridItem xs={12} sm={12} md={9} className={this.state.classes.productContainer}> 
                <GridList cellHeight={180}  cols={4} className={this.state.classes.gridList}>
                  {filteredproducts.map(product =>
                  <GridListTile className={this.state.classes.card}  rows={1} key={product.id}>
                    <Card  rows={1} className={this.state.classes.center}>
                      <CardHeader color="warning">
                        {product.attributes.name}
                      </CardHeader>
                      <CardBody>
                        {product.relationships.images.data.length > 0 &&
                            (() => {
                              const { id } = product.relationships.images.data[0];
                              const image = images.find(image => image.id == id);
                              return image ? (
                                    <img key={images.key} src={`${url}/${image.attributes.styles[2].url}`} />
                              ) : null;
                            })()}
                        <h4 className={this.state.classes.cardTitle}>
                          {product.attributes.display_price}
                        </h4>
                        <Button color="primary" href={url + productUrl + product.attributes.slug }>
                            View
                        </Button>
                      </CardBody>
                    </Card>
                  </GridListTile>
                  )}
                </GridList>
              </GridItem>
            ) : (isLoading)
          }
        </GridContainer>
      </div> 
    </React.Fragment>

2 个答案:

答案 0 :(得分:2)

您是否可以使用具有过滤条件数组的东西,并在handleChange时将过滤条件(分类名称)添加到过滤条件数组中(可以将其作为状态的一部分)

然后使用

let filtered = arr.filter(({taxon})=> {
    return taxon === filterConditions.some(element => element === taxon);
});

因此,您测试分类单元是否与filterConditions数组中的任何分类单元名称匹配 我希望这有助于解决问题

答案 1 :(得分:1)

我设法通过在我的react类之外添加一个let来解决它,并在满足某些参数的情况下使用该函数更改了它的值。

  handleFormChange1 = name => event => {

    //Change filter's value when the button's value has changed to true or false
    this.setState({ 
      isLoading: true, 
      [name]: event.target.checked,
    });

    let miTrue = [name] == "mi" ? event.target.checked : false; 

    filter1 = miTrue === true ? "1," : '';

    console.log('fase 1', 'true', miTrue ,'filter', filter1 ,filter2 , filter3, filter4 ,filter5 , filter6, filter7 ,filter8 , filter9, filter10 ,filter11 , filter12   )
    //refresh the productlist
    this.refreshList();

  };

  refreshList(){

    //Get new data request from API with new filter value's
    axios.get(this.state.url + this.state.include + '&'+ this.state.taxons + filter1 + filter2 + filter3 + filter4 + filter5 + filter6)
    .then(result => this.setState({
      productsData: result.data,
      filteredproducts: result.data.data,
      images: result.data.included,
      isLoading: false,
    }))
    .catch(error => this.setState({
      error,
      isLoading: false
    }));
    //check the value passed on, the value of the event target and if the state has been changed. 
    console.log('fase 3',this.state.mi,this.state.redmi, this.state.go )
  }