如何使用键渲染对象?

时间:2018-12-10 06:11:08

标签: javascript reactjs onblur

这是来自名为FrankerZ的用户的示例代码:

class ExampleComponent extends React.Component {
    onBlur = async () => {
        const results = await axios.get('myhttpendpoint');

        this.setState({
            results
        });
    }
    render() {
        return (
            <div>
                <form>
                    <span className="name"> Search Term: </span>
                    <input id="search-term" value={this.state.value} onBlur={this.onBlur} />
                </form>
                <div id="results">
                    {this.state.results}
                </div>
            </div>)
    }
}

但从本质上讲,我的问题是,如果我的axios.get返回带有键之类的对象

[{{name:test1,data:datadatadata},{name:test2,data:datatatatatata}]

如何在其自己的跨度或div中渲染每个对象? 我尝试使用

这样的地图
this.setState(results.map((item, index) => (<li key = {index}>{item.name}</li>)));   

但是它似乎不起作用。我这样做是因为似乎React无法使用键渲染对象,并且它告诉我使用数组,这是我尝试过的。

3 个答案:

答案 0 :(得分:1)

您应该在render方法或任何其他方法中进行map并在render中调用它,但不要处于set状态。

类似这样的东西

class ExampleComponent extends React.Component {
  onBlur = async () => {
    const results = await axios.get('myhttpendpoint');

    this.setState({
      results
    });
  }
  render() {
    return (
      <div>
        <form>
          <span className="name"> Search Term: </span>
          <input id="search-term" value={this.state.value} onBlur={this.onBlur} />
        </form>
        <div id="results">
          {this.state.results.map(item => (<li key={item.name}>{item.name}</li>))}
        </div>
      </div>)
  }
}

答案 1 :(得分:1)

标记不应进入内部状态。

您的render()应该是这样的。

<div id="results">
  <ul>
    {
      this.state.results.map((item, index) => <li key = {index}>{item.name}</li>)
    }
  </ul>
</div>

确保在构造函数中初始化这样的状态。

this.state = {
      results : []
    };

答案 2 :(得分:0)

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends React.Component {
  state = {
    frank: [] // Basically, you will have a place in the state where you will save your data, which is empty.
  }

  componentDidMount(){
    // This lifecycle method is used to fire requests.
    // Fire your request.
    // get the response.
    // save the data only in the state, don't save ELEMENTS such like li.
    const _result = [
      { id: 1, name: 'Frank1' },
      { id: 2, name: 'Frank2' }
    ];
    this.setState({
      frank: _result
    });
  }

  render() {
    const { frank } = this.state;

    return (
      <div>
        <form>
          <span className="name"> Search Term: </span>
          <input id="search-term" value={this.state.value} onBlur={this.onBlur} />
        </form>
        <div id="results">
         {/*HERE DO MAPPING*/}
         {
            frank.map((item, index) => <li key={index}>{item.name}</li>)
          }
        </div>
      </div>)
  }
}


const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

关注那里的评论。 现场演示:https://codesandbox.io/s/kxv6myl8wo