单击按钮时显示来自 API 的数据。使用 ReactJS

我试图在单击“信息”按钮时显示每个字符的数据。我知道这是因为在onButtonClickHandler函数中它看不到状态。我也尝试过,this.state.person但它给了我一个错误,说“无法读取状态”。如果我尝试,state.person它会给我“未定义”。

最好的方法是什么?谢谢

import React from "react";


export default class FetchActors extends React.Component {

  state = {

    loading: true,

    person: null

  };


  async componentDidMount() {

    const url = "https://swapi.dev/api/people/";

    const response = await fetch(url);

    const data = await response.json();

    this.setState({ person: data.results, loading: false });

  }


  render() {

    if (this.state.loading) {

      return <div>loading...</div>;

    }


    if (!this.state.person.length) {

      return <div>didn't get a person</div>;

    }


   function onButtonClickHandler(state) {

      console.log(state.person);

    };



    return (

      <div>

        <h1>Actors</h1>

        {this.state.person.map(person =>(

        <div>

          <div>

            {person.name}

            <button onClick={onButtonClickHandler}>Info</button>


          </div>


        </div>

        ))}

        <button onClick={onButtonClickHandler}>Enter</button>

      </div>

    );

  }

}


拉莫斯之舞
浏览 130回答 4
4回答

慕哥9229398

如果我错了请纠正我您看到这种情况的最可能原因是 JavaScript 内部的工作方式。语法:function xyz() {}有一个隐含的this也许尝试更改您的代码:function onButtonClickHandler(state) {  console.log(state.person);};到:const onButtonClickHandler = () => {  console.log(this.state.person);};

MMTTMM

您已将函数定义onButtonClickHandler为接受一个参数的函数,并记录person该参数的属性。 函数中的参数与组件的参数state无关。state 在 JavaScript 中,它们是两个完全不相关的变量,只是碰巧具有相同的名称。function onButtonClickHandler(state) {   console.log(state.person);};当button调用时onClick,它将事件作为参数传递。所以你onButtonClickHandler正在记录person事件的属性,这显然不存在。由于您没有使用事件中的任何信息,因此您的函数不应采用任何参数。正如其他人所说,您还应该将此函数移到方法之外render(),以便不会在每次渲染时重新创建它。bind如果您使用箭头函数,则不需要使用建议,因为它们会自动绑定。export default class FetchActors extends React.Component {  /*...*/  onButtonClickHandler = () => {     console.log(this.state.person);  };}里面render()<button onClick={this.onButtonClickHandler}>Enter</button>您还可以将函数内联定义为不带参数的箭头函数:<button onClick={() => console.log(this.state.person)}>Enter</button>如果您是 React 新手,我建议您学习函数组件而不是类组件。我试图在单击“信息”按钮时显示每个字符的数据。一旦我们调用 API,我们就已经加载了每个角色的信息。我们只需要知道要显示哪一个即可。expanded您可以向您添加一个属性,并使用它来存储当前扩展项目的state索引(或id或,无论您真正想要什么)。name当我们循环显示名称和信息按钮时,我们检查该字符是否是展开的字符。如果是这样,我们将显示角色信息。现在onClick按钮的处理程序负责设置state.expanded我们单击它的角色。{this.state.person.map((person, i) =>(<div>  <div>    {person.name}    <button onClick={() => this.setState({expanded: i})}>Info</button>    {this.state.expanded === i && (      <CharacterInfo        key={person.name}        person={person}      />    )}  </div>

料青山看我应如是

有几种方法可以解决您的问题;我会给你更常见的方法。您希望将单击处理程序定义为类(实例)方法,而不是将其声明为渲染方法内的函数(您可以将其定义为渲染方法内的函数,但这可能不是最好的方法超出范围的各种原因)。您还必须将其“this”值绑定到类(实例),因为单击处理程序是异步触发的。最后,添加一个按钮并在单击时触发获取:class Actors extends React.Component {&nbsp; state = {&nbsp; &nbsp; loading: false,&nbsp; &nbsp; actors: undefined,&nbsp; };&nbsp; constructor(props) {&nbsp; &nbsp; super(props);&nbsp; &nbsp; this.fetchActors = this.fetchActors.bind(this);&nbsp; }&nbsp; async fetchActors() {&nbsp; &nbsp; this.setState({ loading: true });&nbsp; &nbsp; const url = "https://swapi.dev/api/people/";&nbsp; &nbsp; const response = await fetch(url);&nbsp; &nbsp; const data = await response.json();&nbsp; &nbsp; this.setState({ actors: data.results, loading: false });&nbsp; }&nbsp; render() {&nbsp; &nbsp; console.log('Actors: ', this.state.actors);&nbsp; &nbsp; return <button onClick={this.fetchActors}>fetch actors</button>;&nbsp; }}

千万里不及你

有时我需要反应一分钟来加载更新的状态。import React from "react";export default class FetchActors extends React.Component {&nbsp; state = {&nbsp; &nbsp; loading: true,&nbsp; &nbsp; person: null&nbsp; };&nbsp; async componentDidMount() {&nbsp; &nbsp; const url = "https://swapi.dev/api/people/";&nbsp; &nbsp; const response = await fetch(url);&nbsp; &nbsp; const data = await response.json();&nbsp; &nbsp; if(!data.results) { // throw error }&nbsp; &nbsp; this.setState({ person: data.results, loading: false }, () => {&nbsp; console.log(this.state.person) // log out your data to verify});&nbsp; }&nbsp; render() {&nbsp; &nbsp; if (this.state.loading || !this.state.person) { // wait for person data&nbsp; &nbsp; &nbsp; return <div>loading...</div>;&nbsp; &nbsp; }else{&nbsp; &nbsp;function onButtonClickHandler(state) { // just make a componentDidUpdate function&nbsp; &nbsp; &nbsp; console.log(state.person);&nbsp; &nbsp; };&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; <h1>Actors</h1>&nbsp; &nbsp; &nbsp; &nbsp; {this.state.person.map(person =>(&nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {person.name}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button onClick={onButtonClickHandler}>Info</button>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; ))}&nbsp; &nbsp; &nbsp; &nbsp; <button onClick={onButtonClickHandler}>Enter</button>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; );&nbsp; }}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript