javascript - 根据查询参数返回匹配的数据
问题描述
我正在使用反应挂钩来动态呈现数据。我正在执行两件事:
一个。从组件的历史道具中获取 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
状态中。请帮忙解决这个问题。
解决方案
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
推荐阅读
- api - 在 Flutter 应用上使用 API 制作最喜欢的功能按钮
- php - Laravel 6.2-根据用户定义的编号对数据进行排序
- jquery - 如何更改我的 jQuery 代码以使 div 顺利跟随我的光标?
- reactjs - 道具改变后反应状态没有改变
- docker - 如何使用私有 Docker 注册表分发自托管应用程序?
- gwt - 在 GWT 中的 Frame 中添加带有 URL 的标头以进行身份验证
- python - 应在至少 2 个输入的列表上调用“连接”层
- amazon-web-services - EC2 和 S3 之间的数据传输是通过公共互联网还是在 AWS 网络内部传输?
- python - Python 添加货币符号 ipywidgets FloatText
- reactjs - 我应该如何改进 React 中的这种行为?