可以通过在子组件中定义一个函数,然后将该函数作为 props 传递给父组件,在子组件中调用该函数来触发更新父组件的数据。

具体步骤如下:

  1. 在父组件中定义一个函数来更新数据,例如:
class ParentComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: []
    };
  }

  updateData = (newData) => {
    this.setState({ data: newData });
  }

  render() {
    return (
      <div>
        <ChildComponent updateData={this.updateData} />
        <DataList data={this.state.data} />
      </div>
    );
  }
}
  1. 在子组件中调用该函数来触发更新,例如:
class ChildComponent extends React.Component {
  fetchData = () => {
    // 异步请求数据
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => {
        // 调用父组件的函数更新数据
        this.props.updateData(data);
      });
  }

  render() {
    return (
      <button onClick={this.fetchData}>更新数据</button>
    );
  }
}

当用户点击子组件中的按钮时,就会触发 fetchData 函数,该函数会发起异步请求数据,并在请求成功后调用父组件传递过来的 updateData 函数来更新父组件的数据。最终,父组件会重新渲染,并将更新后的数据传递给 DataList 组件显示

react里在子组件里触发请求更新父组件的数据怎么做

原文地址: https://www.cveoy.top/t/topic/cSjp 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录