首页 > 解决方案 > 如何在 React 的查询字符串中添加几个条件

问题描述

当我单击按钮(大小:230,240)和标签输入(米色,黑色)时,我尝试创建一个查询字符串(URL),我想在 API 中添加该条件。 在此处输入图像描述

比如 products/shoes?size=230&size=240&color=red 等等。首先,当我单击尺寸按钮时,我只想将条件(&size=230)添加到 API URL(/produts),但它也会更改(重新加载)到新网页。另外,我不确定如何向查询字符串添加几个条件。我只是猜测使用更新反应生命周期?非常感谢您的帮助!

我会把我的代码留在这里以防万一!

updateSize = name => {
    const sizeString = `&size=${name}`;
    const currentURL = this.props.history.location.pathname;
    this.props.history.push(currentURL + `${sizeString}`);
  };

  updateColor = name => {
    const sizeColor = `&color=${this.name.value}`;
    console.log(this.name.value);
    const currentURL = this.props.history.location.pathname;
    this.props.history.push(currentURL + `${sizeColor}`);
  };
div className="sizeLists">
                <button onClick={() => this.updateSize('230')}>230</button>
                <button onClick={() => this.updateSize('235')}>235</button>
                <button onClick={() => this.updateSize('240')}>240</button>
                <button onClick={() => this.updateSize('245')}>245</button>
                <button onClick={() => this.updateSize('250')}>250</button>
                <button onClick={() => this.updateSize('255')}>255</button>
                <button onClick={() => this.updateSize('260')}>260</button>
                <button onClick={() => this.updateSize('265')}>265</button>
                <button onClick={() => this.updateSize('270')}>270</button>
                <button onClick={() => this.updateSize('275')}>275</button>
                <button onClick={() => this.updateSize('280')}>280</button>
              </div>

这是完整的 main.js 代码!

import React, { Component } from 'react';
import './Main.scss';
import COLOR_LISTS from './colorList';
import Products from './ProductsInfo/Products';
import { Link } from 'react-router-dom';

export class Main extends Component {
  constructor() {
    super();
    this.state = {
      productsInfo: [],
    };
  }
  // const API = "DASDDADDAD" => 컴포넌트 마다 다 적용할수x
  componentDidMount() {
    fetch('/data/MainProducts.json', {})
      .then(res => res.json())
      .then(data => {
        this.setState({
          productsInfo: data,
        });
      });
  }

  updateProducts = name => {
    // console.log(e.currentTarget.value);
    fetch(`/data/${name}.json`, {})
      .then(res => res.json())
      .then(data => {
        this.setState({
          productsInfo: data,
          // category_id: '',
        });
      });
    console.log(this.props.history.location.pathname);
    // console.log current URL
  };

  updateSize = name => {
    const sizeString = `&size=${name}`;
    const currentURL = this.props.history.location.pathname;
    this.props.history.push(currentURL + `${sizeString}`);
  };

  updateColor = name => {
    const sizeColor = `&color=${this.name.value}`;
    console.log(this.name.value);
    const currentURL = this.props.history.location.pathname;
    this.props.history.push(currentURL + `${sizeColor}`);
  };

  render() {
    const { productsInfo } = this.state;

    return (
      <div className="MainWrapper">
        <div className="sectionHeader">
          <div className="sectionTitle">
            <div className="sectionTitleCategory">
              <span className="categoryName">Men</span>
              <br />
              <br />
              <span>Men's 의류(12)</span>
            </div>

            <div className="sectionControl">
              <button>필터</button>
              <select name="list" className="productsFilter">
                <option value="newestOrdeer">신상품순</option>
                <option value="hightCostoOder">높은가격순</option>
                <option value="lowCostOrder">낮은가격순</option>
              </select>
            </div>
          </div>
        </div>

        <div className="contentsWrapper">
          <aside className="contentsSide">
            <div className="HorizontalLine" />
            <div className="colors">
              <span>색상</span>
              <ul className="colorLists">
                {COLOR_LISTS.map((color, idx) => {
                  return (
                    <li className="colorLayout" title="베이지" key={idx}>
                      <input type="checkbox" value="color.color_name" />
                      <label
                        className="checkboxLabel"
                        for="checkbox"
                        style={{ backgroundColor: color.colorProps }}
                      />
                      <span className="productColor">{color.color_name}</span>
                    </li>
                  );
                })}
              </ul>
            </div>
            <div className="sizes">
              <div className="HorizontalLine" />
              <span>사이즈&lt;/span>
              <div className="sizeLists">
                <button onClick={() => this.updateSize('230')}>230</button>
                <button onClick={() => this.updateSize('235')}>235</button>
                <button onClick={() => this.updateSize('240')}>240</button>
                <button onClick={() => this.updateSize('245')}>245</button>
                <button onClick={() => this.updateSize('250')}>250</button>
                <button onClick={() => this.updateSize('255')}>255</button>
                <button onClick={() => this.updateSize('260')}>260</button>
                <button onClick={() => this.updateSize('265')}>265</button>
                <button onClick={() => this.updateSize('270')}>270</button>
                <button onClick={() => this.updateSize('275')}>275</button>
                <button onClick={() => this.updateSize('280')}>280</button>
              </div>
              <div className="HorizontalLine" />
            </div>
          </aside>

          <main className="contentsBody">
            <div className="contentsLink">
              <div className="viewAll">
                <Link
                  to={{
                    pathname: '/products',
                    state: { message: 'hello, im a passed message!' },
                  }}
                >
                  <button onClick={() => this.updateProducts('MainProducts')}>
                    {/* <button onClick={this.updateProducts} value="acc"> 
                    and then using e.currentTarget.value same as top one. */}
                    <span>전체 보기</span>
                  </button>
                </Link>
              </div>
              <div className="Shoes">
                <Link
                  to={{
                    pathname: '/products/shoes',
                    state: { message: 'hello, im a passed message!' },
                  }}
                >
                  <button
                    onClick={() => this.updateProducts('MainProductsShoes')}
                  >
                    <span>신발</span>
                  </button>
                </Link>
              </div>
              <div className="Clothes">
                <Link
                  to={{
                    pathname: '/products/clothing',
                    state: { message: 'hello, im a passed message!' },
                  }}
                >
                  <button
                    onClick={() => this.updateProducts('MainProductsClothing')}
                  >
                    <span>옷&lt;/span>
                  </button>
                </Link>
              </div>
              <div className="Supplies">
                <Link
                  to={{
                    pathname: '/products/acc',
                    state: { message: 'hello, im a passed message!' },
                  }}
                >
                  <button
                    onClick={() => this.updateProducts('MainProductsAcc')}
                  >
                    <span>악세사리</span>
                  </button>
                </Link>
              </div>
            </div>
            <article className="productsMapping">
              {productsInfo &&
                productsInfo.map((product, idx) => (
                  <Products key={idx} productInfo={product} />
                ))}
            </article>
          </main>
        </div>
      </div>
    );
  }
}

export default Main;
import React, { Component } from 'react';
import { withRouter, Link } from 'react-router-dom';

export class Products extends Component {
  render() {
    const { productInfo } = this.props;
    // child에서 선택한 값을 parent state에 값을 반영하기 위해서
    //  어떤 props를 parent에서 child로 전달할 수 있을지 생각해보세요!
    return (
      <Link
        to={`/products/${productInfo.category_id}/${productInfo.product_id}`}
      >
        <div className="productsContainer">
          <div className="productLayout">
            <div className="productImage">
              <img alt="production" src={productInfo.image} />
            </div>
            <div className="productInfo">
              <div className="productInfoDisplay">
                <div className="productStatus">
                  <span>{productInfo.ecoFriendly}</span>
                </div>
                <div className="productName">
                  <span>{productInfo.title}</span>
                </div>
                <div className="productCategory">
                  <span>{productInfo.sub_title}</span>
                </div>
                <div className="productColorChoices">
                  <span>{productInfo.color_kind} 컬러</span>
                </div>
              </div>
              <div className="productPrice">
                <span>11,900 원&lt;/span>
              </div>
            </div>
          </div>
        </div>
      </Link>
    );
  }
}

export default withRouter(Products);

标签: reactjs

解决方案


推荐阅读