首页 > 解决方案 > 根据查询参数返回匹配的数据

问题描述

我正在使用反应挂钩来动态呈现数据。我正在执行两件事:

一个。从组件的历史道具中获取 URL 参数。

湾。从组件的历史道具中获取状态数据,该道具返回给我一个对象数组,例如:

current_data: Array(2)
0: {registration_data: {…}, company_name: "Test"}
1: {registration_data: {…}, company_name: "Sample"}
lastIndex: (...)
lastItem: (...)
length: 2
__proto__: Array(0)

我需要实现的是,将数据从current_data对象中渲染出来,与我的 URL 查询参数匹配。我for loop用来迭代我的数组。我知道这是一个菜鸟问题,但有点坚持以获得所需的输出。

import React, {useState, useEffect} from 'react';

const ViewRegistrations = (props) => {
    const [queryParam, setParam] = useState('');
    useEffect(() => {
        const queryParam = new URLSearchParams(props.location.search).get('registration');
        setParam(queryParam);
    })

    const [dataRecieved, setData] = useState( [] );

    useEffect(() => {
        const data = props.location.state.current_data;
        // const testData
        for(var i = 0; i< data.length; i++){
            console.log(data[i] === queryParam)
        }
    });

    return (
        <div>
            {}
        </div>
    )
}

export default ViewRegistrations;

该语句console.log(data[i] === queryParam)每次都返回我的布尔值。我希望将与查询参数匹配的数组数据存储在dataRecieved状态中。请帮忙解决这个问题。

标签: javascriptreactjs

解决方案


One solution to your question would be as follows 1. First of all get your desired queryParam on the mount of the component (I am also unsure about your usage of the useState hook, the second variable should be the first one with the 'set' added), like so:

const [queryParam, setQueryParam] = useState('');  
useEffect(() => {
const query = new URLSearchParams(props.location.search).get('registration');
            setQueryParam(query);
}, []) // don't forget to add an empty dependency array so it runs only once

Secondly, you then do your condition of match with another useEffect

useEffect(() => {
const data = props.location.state.current_data;
if (data && queryParam)
for(var i = 0; i< data.length; i++){
    data[i] === queryParam ? setDataReceived([...dataReceived, data[i]) : null;
  }
}, [queryParam])

And lastly you do whatever you want in terms of displaying them, you could achieve this with map in your component, something like

{dataReceived.length && dataReceived.map((data) => <whatever>data</whatever>)}

I am not 100% sure this is a working version, maybe some tweaks should be made, but this gives you an idea


推荐阅读