我正在尝试使用 npm文件系统列出服务器上给定路径的文件和文件夹。据我了解,浏览器(客户端)不允许使用 Javascript 访问文件系统,但如果我从服务器运行 javascript,则应该允许访问文件系统。
因此,我创建了一个 ReactJS 应用程序,按照此处的教程执行服务器端渲染(或者您可以获取 git 代码并在此处开箱即用地构建/运行它)。
我可以在禁用浏览器的 javascript 的情况下调用 Date.now() 等基本函数,证明 javascript 正在服务器上运行,但是当我插入以下代码时,我收到错误。
为什么我的服务器代码无法识别 fs?
组件代码:
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as userActions from '../actions/user'
import { Link } from 'react-router-dom'
import './FirstPage.css'
var fileSystem = require("file-system")
class FirstPage extends Component {
render() {
fileSystem.recurse('./', ['*.*'],
function(filepath, relative, filename) {
if (filename) {
console.log("FILE"+filename); …Run Code Online (Sandbox Code Playgroud) 由于某些原因,将变量“ row”分配为空时,引发以下错误:
空白文本节点不能作为的子级出现。确保源代码每一行的标记之间没有多余的空格
render(){
if(typeof(this.props.settings) ==="undefined"||Object.keys(this.props.settings).length==0)
{
//We haven't asked for Admins yet, so they don't exist.
row ='';
}
else {
...
row = nameArray.map((data,index) =>
<tr key={index}><td>{data}</td>
<td>{idArray[index]}</td>
<td><div className="link_decoration" onClick={()=>this.props.removeRequest(idArray[index])}>Remove</div></td>
</tr>
);
}
return(
<div>
<table>
<tbody><tr><th>Name</th><th>SSO</th><th></th></tr>{row}</tbody></table>
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
我可以通过创建占位符而不是设置row =''来解决错误:
nameArray.push("PlaceHolder");
idArray.push("12345");
row = nameArray.map((data,index) =>
<tr key={index}><td>{data}</td>
<td>{idArray[index]}</td>
<td><div className="link_decoration" onClick={()=>this.props.removeRequest(idArray[index])}>Remove</div></td>
</tr>
);
}
Run Code Online (Sandbox Code Playgroud)
但一定有更好的方法...
尝试使用 ReactJS 生成表,并且在该表中我想要一个唯一的键来标识每一行(如 ReactJS 推荐的那样)。以下代码运行并生成我想要的表,但出现以下错误:
Warning: 'Each child in an array or iterator should have a unique "key" prop'
Run Code Online (Sandbox Code Playgroud)
查看我生成的 HTML,“key”字段确实不存在。我也试过 key={index} 但它也不起作用
export class Tablecontent extends Component{
constructor(props){
super(props);
this.state={
fileinfo:'null'
}
}
render(){
//const fileinfo = this.props.rows;
const fileinfo = ['myFile1.doc','myFile2.doc'];
var row='';
console.log("FILEINFO:"+fileinfo);
if(fileinfo=='null')
{
row ='';
}
else {
row = fileinfo.map((data,index) =>
<tr>
<td key="filename_{index}">{data}</td>
<td key="date_{index}">2/12/2017</td>
<td key="size_{index}">2.1 MB</td>
</tr>
);
}
return(
<div>
<table>
<tbody>
<tr>
<th>Name</th>
<th>Date Created</th>
<th>Size</th>
</tr>{row}</tbody>
</table>
</div> …Run Code Online (Sandbox Code Playgroud)