如何在子组件的按钮单击时重新渲染父组件

我正在学习 React,但我仍然认为自己是一个初学者。我的目标是单击子组件上的按钮,以便我可以重新渲染父组件。这是我的代码。


父组件


import React, { Component } from 'react';

import Activity from './Components/Activity'


class App extends Component {

  state = {

    activity: ''

  }


  handleClick = () => {

    // I have read that forceUpdate is discouraged but this is just an example

    this.forceUpdate()

  }


  async componentDidMount() {

    const url = 'http://www.boredapi.com/api/activity/'

    const response = await fetch(url);

    const data = await response.json();

    this.setState({

      activity: data.activity

    })

  }


  render() {

    return (

      <div>

        <Activity act={this.state.activity} click={this.handleClick}/>

      </div>

    );

  }

}


export default App;

子组件


import React, { Component } from 'react';


class Activity extends Component {


  render() {

    return (

      <div>

        <h1>Bored? Here is something to do</h1>

        <p>{this.props.act}</p>

        <button onClick={this.props.click}>Something Else</button>

      </div>

    );

  }

}


export default Activity;

正如您所看到的,我正在尝试单击一个按钮,以便我可以再次获取并在我的子组件上呈现不同的活动。我试图让我的孩子组件保持无状态,但如果保持它无状态没有意义或者完全错误,我很想知道。


拉丁的传说
浏览 99回答 2
2回答

心有法竹

您可以尝试将获取函数移到 componentDidMount 之外例如:&nbsp; handleClick = () => {&nbsp; &nbsp; this.fetchdata();&nbsp; }&nbsp; async fetchdata(){&nbsp; &nbsp; const url = 'http://www.boredapi.com/api/activity/'&nbsp; &nbsp; const response = await fetch(url);&nbsp; &nbsp; const data = await response.json();&nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; activity: data.activity&nbsp; &nbsp; })&nbsp; }&nbsp; componentDidMount() {&nbsp; &nbsp; this.fetchdata();&nbsp; }

慕娘9325324

您可以创建一个类方法来获取新活动,在应用程序首次安装后调用它,componentDidMount()并在从子组件调用它时再次调用它Activity。您应该在问题中提到,您提出的每个请求的响应正文都是不同的。import React, { Component } from 'react';import Activity from './Activity'class App extends Component {&nbsp; state = {&nbsp; &nbsp; activity: ''&nbsp; }&nbsp; handleClick = () => {&nbsp; &nbsp; this.getActivity()&nbsp; }&nbsp; componentDidMount() {&nbsp; &nbsp; this.getActivity();&nbsp; }&nbsp; async getActivity() {&nbsp; &nbsp; const url = 'https://www.boredapi.com/api/activity/'&nbsp; &nbsp; const response = await fetch(url);&nbsp; &nbsp; const data = await response.json();&nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; activity: data.activity&nbsp; &nbsp; })&nbsp; }&nbsp; render() {&nbsp; &nbsp; console.log(this.state);&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; <Activity act={this.state.activity} click={this.handleClick}/>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; );&nbsp; }}export default App;这也是一个沙箱:https://codesandbox.io/s/dreamy-noether-q98rf? fontsize=14&hidenavigation=1&theme=dark
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript