当我在反应中按下获取按钮时,对象数组没有被获取

array of objects are not being fetching when i press the fetch button in react

我在 运行 执行此操作时遇到错误!!它说 cannot read 属性 of map undefined 。我想 运行 按下按钮时的获取功能!然后对象将显示......但似乎没有那样......它会出错

class App extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            robots: []
        }
        this.fetchData = this.fetchData.bind(this);
    }

//fetch data function . linked with button shdfvjksvda kvahsdksa
    fetchData=()=> {
        fetch('https://jsonplaceholder.typicode.com/users')
        .then(response => {  response.json() })
        .then((data) => {
            console.log(data);
           this.setState({ robots: data })
        }
        )
        ;

    }

    render() {
        return (

           <div>
            <button onClick={this.fetchData}>Fetch</button>
            <p>
                {this.state.robots.map(el => {
                    return <div key={el.id}>
                       <span>{el.email}</span>
                       <span>{el.name}</span>
                       <span>{el.id}</span>
                    </div>
                })}
            </p>
        </div>
        )
    }

}

havscjhuvsakdvasdu
export default App;

您在链接承诺时错过了 return 语句。

fetchData=()=> {
    fetch('https://jsonplaceholder.typicode.com/users')
    .then(response => {  return response.json() })
    .then((data) => {
        console.log(data);
       this.setState({ robots: data })
    }
    )
    ;

}

正如 Easwar 指出的那样,您 return 没有从第一个 .then() 中学到任何东西。然而,理想的解决方案是省略 { 括号,使其自动具有 return 值。这有点干净,更具可读性:

fetchData = () => {
    fetch('https://jsonplaceholder.typicode.com/users')
        .then(response => response.json())
        .then((data) => {
            console.log(data);
            this.setState({ robots: data })
        });
}

Arrow functions can have either a "concise body" or the usual "block body".

In a concise body, only an expression is specified, which becomes the implicit return value. In a block body, you must use an explicit return statement.

有关它们如何工作的更多信息,请参阅 documentation for arrow functions