我有一个JSON:
{
"books": {
"book1": {
"id": 1,
"name": "Sample",
"author": "Somebody",
"genre": "Tales"
},
"book2": {
"id": 2,
"name": "Winter",
"author": "Ted"
}
}
}
我在组件中导入它:
import data from './books.json';
然后尝试在页面上显示它:
class Home extends Component {
render(){
const carNode = () => {
return (
<tr>
<th scope="row">{data.books.book1.id}</th>
<td>
<p>
<Link
to={"books/"+data.books.book1.id}
key={data.books.book1.id}>
{data.books.book1.name}
</Link>
</p>
<p className="author">{data.books.book1.author} </p>
</td>
</tr>
)
};
return (
<div className="container-fluid content-main">
<div className="row">
<div className="col-xl-12">
.........
<p>{carNode}</p>
.........
</div>
</div>
</div>
);
}
}
但是这段代码没有用数据填充我的表格。当json在我的index.jsx中正确时,代码工作正常。我也安装并尝试使用json-loader。你能告诉我这里应该使用什么代码吗?
答案 0 :(得分:0)
您将其声明为函数,但不要将其称为函数:
fileContent.append(pack.getSurname() + "," + pack.getFirstname() + "," + pack.getScout_no() + "," +
pack.getgroup() + "," + pack.getDob() + "," + '"' + "=ROUNDDOWN(((TODAY()-E"+row+")/365),1)" + '"' + "," +
pack.getstartDate() + "," + '"' + "=ROUNDDOWN(((TODAY()-G"+row+")/365),1)" + '"' + "," +
'"' + "=EDATE(E"+row+",216)" + '"' + "\n");
答案 1 :(得分:0)
为什么要将其存储为JSON?你需要导出才能导入。你可以做点什么
export default {
"books": {
"book1": {
"id": 1,
"name": "Sample",
"author": "Somebody",
"genre": "Tales"
},
"book2": {
"id": 2,
"name": "Winter",
"author": "Ted"
}
}
}
并将文件从.json文件更改为.js
答案 2 :(得分:0)
这对我有用:
const carNode = Object.keys(data.books).map(item =>
{return (
<tr>
<th>{data.books[item].id}</th>
<td>
<p>
<Link
to={"books/"+data.books[item].id}
key={data.books[item].id}
>{data.books[item].name}</Link>
</p>
<p className="author">{data.books[item].author}</p>
</td>
</tr>
)}
)
答案 3 :(得分:0)
您可以使用json加载程序将json导入组件。 import a Json file in a React Component
或者,您可以使用javascript对象而不是json将其导入组件中。像:
// books.js
export default {
"books": {
"book1": {...},
"book2": {...},
}
}
现在,您可以在组件中导入它:
import data from './books'