如何从JSON Nodejs后端填充React数组

时间:2018-04-09 08:59:51

标签: javascript json node.js reactjs rest

我对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文件中?

3 个答案:

答案 0 :(得分:1)

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

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

然后在前端,您可以使用res.map(x => x.name)

获取每个证书的名称

答案 1 :(得分:0)

您可以使用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>
        );
    }
}

答案 2 :(得分:0)

理想情况下,您希望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>
    );
  }

希望这有帮助。