reactjs 在ReactRouterV6中,从前端到后端传递多个参数查询的最佳方式是什么

mgdq6dx1  于 2023-03-01  发布在  React
关注(0)|答案(1)|浏览(124)

我正在做一个有多个标签的求职应用程序,点击它可以使用MERN过滤求职信息。我正在尝试将多个查询字符串传递到后端并过滤数据,但我不知道如何从参数中提取并在后端进行解构。目前我将参数制作成数组。
特别是当我单击“Vue”和“Sass”这两个工具时,它会返回["tool", "Vue"], ["tool", "Sass"],,但我希望在后端合并{tools:“Vue”,“Sass”}来轻松过滤。

主屏幕.js

import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useSearchParams } from 'react-router-dom';
import Filterbar from '../components/Filterbar';
// import PhotosnapIcon from '~/images/photosnap.svg';
import { listJobs } from '../actions/jobActions';

import './HomeScreen.scss';

export default function HomeScreen() {
  const dispatch = useDispatch();

  const jobList = useSelector((state) => state.jobList);
  const { loading, error, jobs } = jobList;

  let [searchParams, setSearchParams] = useSearchParams();

  const params = [];

  searchParams.forEach((value, key) => {
    params.push([key, value]);
  }); // this returns ["level", "Junior"], ["language", "JavaScript"], ["tool", "Sass"]

  useEffect(() => {
    dispatch(listJobs(params));
    console.log(jobs);
  }, [dispatch]);

  const addQuery = (key, value) => {
    setSearchParams((prev) => [...prev.entries(), [key, value]]);
  };

  return (
    <>
      <Filterbar />
      <ul>
        {jobs.map((job) => (
          <li className={job.featured ? 'post featured' : 'post'} key={job._id}>
            <div className="post__img-container">
              <img src={job.logo} alt="photosnap" />
            </div>
            <div className="post__upper-container">
              <div className="post__company-container">
                <h2 className="post__company">{job.company}</h2>
                {job.new && <span className="post__label new">new!</span>}
                {job.featured && (
                  <span className="post__label featured">featured</span>
                )}
              </div>
              <h3 className="post__job-title">{job.position}</h3>
              <div className="post__data">
                <span className="post__date">{job.postedAt}</span>
                <div className="post__dot"></div>
                <span className="post__hours">{job.contract}</span>
                <div className="post__dot"></div>
                <span className="post__location">{job.location}</span>
              </div>
            </div>
            <div className="post__lower-container">
              <button
                className="post__category"
                name="role"
                value={job.role}
                onClick={(e) => addQuery('role', e.currentTarget.value)}
              >
                <span>{job.role}</span>
              </button>{' '}
              <button
                className="post__category"
                value={job.level}
                onClick={(e) => addQuery('level', e.currentTarget.value)}
              >
                <span>{job.level}</span>
              </button>
              {job.languages.map((language) => (
                <button
                  className="post__category"
                  name="language"
                  value={language}
                  onClick={(e) => addQuery('language', e.currentTarget.value)}
                >
                  <span>{language}</span>
                </button>
              ))}
              {job.tools.map((tool) => (
                <button
                  className="post__category"
                  name="tool"
                  value={tool}
                  onClick={(e) => addQuery('tool', e.currentTarget.value)}
                >
                  <span>{tool}</span>
                </button>
              ))}
            </div>
          </li>
        ))}
      </ul>
    </>
  );
}

作业操作.js

import axios from 'axios';

import {
  JOB_LIST_REQUEST,
  JOB_LIST_SUCCESS,
  JOB_LIST_FAIL,
} from '../constants/jobConstants';

export const listJobs =
  (params = '') =>
  async (dispatch) => {
    try {
      dispatch({ type: JOB_LIST_REQUEST });

/// NOT SURE about the url
      const { data } = await axios.get(`/api/jobs?q=${params}`);
      dispatch({
        type: JOB_LIST_SUCCESS,
        payload: data,
      });
    } catch (error) {
      dispatch({
        type: JOB_LIST_FAIL,
        payload:
          error.response && error.response.data.message
            ? error.response.data.message
            : error.message,
      });
    }
  };
  • 〉后端〉控制器〉jobs.js:不确定要添加什么以及如何解构数组以查找列表 *
import ErrorResponse from '../utils/errorResponse.js';
import asyncHandler from '../middleware/async.js';
import Job from '../models/Job.js';

// @desc Get all jobs
// @routes GET /api/jobs
// @access Public
const getJobs = asyncHandler(async (req, res, next) => {
  const jobs = await Job.find({});
  res.json(jobs);
});

export { getJobs, getJob, createJob, deleteJob, updateImage, updateJob };
xuo3flqw

xuo3flqw1#

您可能希望使用URLSearchParams并将其传递给axios.get,因为您有一个数组形式的键值对。

const queryParams = new URLSearchParams(params);

const { data } = await axios.get("/api/jobs", { params: queryParams });

或者你也可以把它作为对象发送。

const { data } = await axios.get("/api/jobs", {
  params: { level: "Junior", language: "JavaScript" },
});

相关问题