首页 > 解决方案 > 根据点击的链接显示来自 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 文件显示相关信息。

标签: jsonreactjsparsing

解决方案


您可以通过链接传递查询,然后直接从 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>
    );
  }
}

推荐阅读