json - 根据点击的链接显示来自 json 文件的不同数据
问题描述
反应.js
在主页面 example.js 上有 4 个链接:link1、link2、link3、link4
当用户单击其中一个链接时,它们会被发送到一个名为 template.js 的站点。
每个链接都将用户发送到同一个站点 template.js,但是数据会根据单击的链接而有所不同。
我试图只显示我的一个 .json 文件中的全部数据,没有任何功能和样式 - 但我没有得到任何响应......我试过了:
var data = require(url);
for(var i = 0; i < data.length; i++) {
var obj = data[i];
console.log("Name: " + obj.first_name + ", " + obj.last_name);
}
或者
fetch(url)
.then(response => response.json().then(data => ({status:
response.status, body: data})))
.then(object => console.log(object));
或者
fetch(url)
.then(response = response.json())
问题:
我将如何告诉 template.js 文件显示相关信息。
解决方案
您可以通过链接传递查询,然后直接从 url 读取。我这样做:
您的链接
// Here we want to send our search terms, this is just an example with 'someId'
<a src="/template?first_name=john"></a>
<a src="/template?first_name=jenny"></a>
<a src="/template?first_name=gabriel"></a>
<a src="/template?first_name=jose"></a>
您可以使用 window.location.search 或 window.location.hash 读取搜索值,具体取决于您的路由器。
我更喜欢使用查询字符串模块中的解析函数
你的模板
import React, { Component } from 'react';
import * as qs from 'query-string';
class Dashboard extends Component {
render() {
const {
location,
} = this.props;
const { search } = location;
const query = qs.parse(search, { ignoreQueryPrefix: true });
const info = YOURJSONDATA.filter(data => (
// Here we compare the field we want with the query search
data.first_name === query.first_name
));
return (
<div>
{
!!(info) && info.map(o => (<div>{o.first_name}</div>))
}
</div>
);
}
}
推荐阅读
- google-apps-script - 无法正确格式化日期谷歌应用脚本
- r - 如何在 Linux 服务器上的 R 中验证 BigQuery (bigrquery)
- python - Python - opencv 在 Canny 边缘图像周围绘制边界框
- .net-core - 放置方法 - CORS 策略阻止了从源获取的访问权限
- java - java - 如何使用Java获取JSON文件中多个对象的相同属性?
- javascript - 部分可见时滚动闪烁
- keycloak - Keycloak 在 Spring Boot 项目中无法处理根 URL
- gitlab - npm install 后 Gitlab Shared Runner docker build
- ssl - 在入口控制器为超集启用 SSL 终止
- azure-pipelines - 在 Azure 数据工厂中使用筛选器活动筛选数据的问题