【问题标题】:ReactJS display fetch response onClickReactJS 显示获取响应 onClick
【发布时间】:2017-10-05 13:18:32
【问题描述】:

我正在开发一个 ReactJS 项目,您可以在按下生成按钮时生成随机活动。我正在获取我的 api 以显示其中的一些数据。这工作正常。现在我想每次单击生成按钮(位于主组件中)时都进行获取并显示返回的数据。因此生成按钮必须执行新的获取并刷新组件。默认情况下它必须为空。我搜索了一段时间,找不到相关的答案。你们中的一些人可以帮助我吗?谢谢。

获取组件

import React from "react";

export class ItemLister extends React.Component {
    constructor() {
        super();
        this.state = { suggestion: "" };
    }

    componentDidMount() {
        fetch("......./suggestions/random", {
            method: "GET",
            dataType: "JSON",
            headers: {
                "Content-Type": "application/json; charset=utf-8"
            }
        })
            .then(resp => {
                return resp.json();
            })
            .then(data => {
                this.setState({ suggestion: data.suggestion });
            })
            .catch(error => {
                console.log(error, "catch the hoop");
            });
    }

    render() {
        return <h2>{this.state.suggestion}</h2>;
    }
}

主页组件

import React from "react";
import { ItemLister } from "./apiCall";

export class Home extends React.Component {
    constructor(props) {
        super(props);
        console.log();
        window.sessionStorage.setItem("name", this.props.params.name);
        window.sessionStorage.setItem("token", this.props.params.token);
    }

    render() {
        return (
            <div className="contentContainer AD">
                <table>
                    <thead>
                        <tr>
                            <th>
                                <p>Het is heel leuk als het werkt!</p>
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>
                                <ItemLister />
                            </td>
                        </tr>
                    </tbody>
                </table>
                <div className="container center">
                    <button>GENERATE</button>
                    <button>SAVE</button>
                    <button>MATCH</button>
                </div>
            </div>
        );
    }
}

【问题讨论】:

  • 您是否仍然面临渲染建议的任何问题?
  • 不,不带渲染。主要问题是在生成按钮中设置一个 onClick 以连接 fetch 功能。
  • 您希望每次通过单击生成按钮来刷新 ItemListener 组件。对吗?
  • 没错

标签: reactjs fetch


【解决方案1】:

我会说您将获取逻辑移动到home 组件并在home 组件中保持状态,就像您在Itemlister 组件中所做的那样。然后您所要做的就是将您的状态传递给Itemlister 组件。您的 home 组件将如下所示

export class Home extends React.Component {
constructor(props) {
    super(props)
    this.state = {suggestion: ""}
    ...
}

componentDidMount(){
  // For initial data
  this.fetchData();
}

fetchData = () => {
  fetch("......./suggestions/random", {
    method: "GET",
    dataType: "JSON",
    headers: {
      "Content-Type": "application/json; charset=utf-8",
    }
  })
  .then((resp) => {
    return resp.json()
  }) 
  .then((data) => {
    this.setState({ suggestion: data.suggestion })                    
  })
  .catch((error) => {
    console.log(error, "catch the hoop")
  })
}

render() {
    return (
        ...
                <tbody >
                   // Pass state to itemlister like this
                    <tr><td><ItemLister suggestion={this.state.suggestion}/></td></tr>
                </tbody>
            </table>
            <div className="container center">
                // Add event handler here. On every click it will fetch new data
                <button onClick={this.fetchData}>GENERATE</button>
                <button>SAVE</button>
                <button>MATCH</button>
            </div>
        </div>
    )
  }
}

而您的ItemLister 组件有责任通过道具显示数据。

export class ItemLister extends React.Component {
    constructor() {
    super();
    }

    render() {
    return(
      <h2> 
        {this.props.suggestion}
      </h2>
      )
     }
    } 

根据dubes在评论中的建议,如果你不想在这个组件中保持任何状态,那么你可以像这样制作这个功能组件

function ItemLister(props) {
  return <h2> 
            {props.suggestion}
          </h2>;
}

【讨论】:

  • 这是一种更简洁的方法(并且根据我的理解推荐了一种)。一个建议:ItemListener 组件可以是functional component
  • 这很好用,但是默认情况下它不是空的。它在页面加载时进行提取,因此在用户按下生成之前已经有数据。
  • @StevenvanEck 如果您希望它默认为空,那么只需从 componentDidMount 函数中删除 this.fetchData(); 行。
  • 但是,在被要求之前获取数据,不会有可能获取过多数据并冒着性能和内存消耗的风险吗?
【解决方案2】:

我不太确定我是否理解正确...但是由于您将 fetch 添加到 react 扩展类中,因此您可以将其呈现在 home 组件中,如下所示:

  state = {
    visible: false
  }

  generateItem() {
    if (this.state.visible) {
      return <ItemLister />
    }
    return <h2>nothing to show</h2>
  }

  render() {
    return(
      <div>
        <button onClick={() => this.setState({visible: true})}>Click</button>
        {this.generate()}
      </div>
    )
  }

onClick 函数会在用户每次点击它时更新状态,并且会发生新的重新渲染,因此会使用新的随机词再次调用 generateItem。

希望这就是您要搜索的内容。

【讨论】:

  • 谢谢,这对我帮助很大,但是每次单击按钮时我都需要进行提取。现在它只会获取第一次点击。
  • 再次点击按钮后应该会再次调用 fetch
猜你喜欢
  • 2021-01-26
  • 2018-11-20
  • 1970-01-01
  • 2020-04-08
  • 1970-01-01
  • 2020-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多