【问题标题】:How to populate React array from JSON Nodejs back end如何从 JSON Nodejs 后端填充 React 数组
【发布时间】:2018-09-18 15:04:02
【问题描述】:

我对 React 很陌生。 我已经设置了一个 Nodejs 后端,它读取以下格式的 JSON 文件:

{
    "cert1" : {
        "name" : "www.google.com",
        "state" : "valid",
        "days" : "482"
    },
    "cert2" : {
        "name" : "www.facebook.com",
        "state" : "valid",
        "days" : "182"
    },
    .
    .
    .
}

我想在表格中显示这些数据,首先需要将其放入数组中。我已经设法使用以下代码显示www.google.com

class App extends Component {
  state = {
    name  : '',
    state : '',
    days  : '',
    response : ''
  };


  componentDidMount() {
    this.callApi()
      .then(res => {
        this.setState({ 
          response: res.cert1.name
        })
      })
      .catch(err => console.log(err));
  }


  callApi = async () => {
    const response = await fetch('/list-certs');
    const body = await response.json();

    if (response.status !== 200) throw Error(body.message);

    return body;
  };

  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <p className="App-intro">
          {this.state.response}
        </p>
      </div>
    );
  }
}

如何映射整个 JSON 文件并使用所有条目填充一些数组?现在我正在调用 res.cert1.name 但 JSON 文件中的每个证书条目都有不同的名称(cert1、cert2、cert3 等)所以我如何将 res.cert1.name 转换为对 JSON 文件中任何证书条目的通用调用?

【问题讨论】:

标签: javascript json node.js reactjs rest


【解决方案1】:

您可以使用 Object.keysArray.map 从您的 JSON 对象构建一个数组,并在其上映射以呈现您的元素。

示例:

class App extends Component {
    state = {
        name  : '',
        state : '',
        days  : '',
        response : []
    };


    componentDidMount() {
        this.callApi()
            .then(res => {
                this.setState({
                    response: Object.keys(res).map(key=>({...res[key], id:key}))
                })
            })
            .catch(err => console.log(err));
    }


    callApi = async () => {
        const response = await fetch('/list-certs');
        const body = await response.json();

        if (response.status !== 200) throw Error(body.message);

        return body;
    };

    render() {
        return (
            <div className="App">
                <div className="App-header">
                    <img src={logo} className="App-logo" alt="logo" />
                    <h2>Welcome to React</h2>
                </div>
                <p className="App-intro">
                    {this.state.response.map(item => (<p>{item.name}</p>))}
                </p>
            </div>
        );
    }
}

【讨论】:

  • 感谢您的帮助,但我在浏览器中收到一个错误,提示地图不是函数
  • 抱歉,响应被初始化为字符串。编辑答案。错误就在这一行,对吧? {this.state.response.map(item =&gt; (&lt;p&gt;{item.name}&lt;/p&gt;))}
  • 我想是的,我已经按照上面的建议将我的 JSON 文件更改为数组格式,并将我的响应变量更改为空列表
  • 如果您的 JSON 现在是一个数组,您可以跳过 componentDidMount 方法中的 Object.keys()....
【解决方案2】:

理想情况下,您希望 JSON 是一个数组,而不是对象的对象:

[
    {
        "name" : "www.google.com",
        "state" : "valid",
        "days" : "482"
    }, {
        "name" : "www.facebook.com",
        "state" : "valid",
        "days" : "182"
    }
]

然后在前端您可以使用res.map(x =&gt; x.name) 获取每个证书的名称

【讨论】:

    【解决方案3】:

    理想情况下,您希望 json 结果是一个数组。

    在从 api 检索时,您可以使用结果设置状态。

    这取决于你的 api 是什么样子,但是如果你返回你的 json 对象,其中包含一个项目数组并将其存储在状态中......

    componentDidMount() {
        this.callApi()
          .then(res => {
            this.setState({ 
              results: res.body
            })
          })
          .catch(err => console.log(err));
      }
    

    然后您可以在渲染中执行地图功能。

    render() {
        return (
          <div className="App">
            <div className="App-header">
              <img src={logo} className="App-logo" alt="logo" />
              <h2>Welcome to React</h2>
            </div>
            <p className="App-intro">
              { this.state.results.map((row) => {
                   return <p>{row.name}</p>
              }) }
            </p>
          </div>
        );
      }
    

    希望这会有所帮助。

    【讨论】:

    • 感谢您的帮助,但我在浏览器中遇到错误:App.js:44 Uncaught TypeError: this.state.response.map is not a function at App.render (App .js:44) 在 ReactCompositeComponent.js:793 在 measureLifeCyclePerf (ReactCompositeComponent.js:74)
    • 我已将响应变量更改为数组,现在没有错误但没有显示任何内容
    • 嗨@tnoel999888 这可能是因为状态结果不是以数组开头...在设置状态下使用 this.setState({results:[]});还要确保来自服务器的响应以数组而不是对象的形式返回。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-16
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多