javascript - 从子进程中的 Promise.then 触发父进程中的 setState 函数

标签 javascript reactjs

我正在尝试从 child promise 中的 parent 找到 setState 的解决方案。

组件

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      transition: false
    };
  }

  handleTransition = () => {
    this.setState(state => ({ transition: !state.transition }));
  };

  render() {
    return <Child handleTransition={this.handleTransition} />;
  }
}

其中 this.props.handleTransition 将从 child component 触发,如下

class Child extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  onSubmit = event => {
    firebase
      .doCreateUserWithEmailAndPassword(email, password)
      .then(() => {
        // Trigger this.props.handleTransition here
      })
      ...

其中 this.props.handleTransition 想要通过 onSubmitthen 触发

如果您需要更多详细信息,请告诉我?我不想使用库或包来实现此目的,但如果它使生活更轻松,我可能会考虑。 Redux 可能是最好的选择,但除非必要,否则我宁愿不这样做。

注意:this.props.handleTransition(); 完成了这项工作,但 esLint 返回错误 必须使用解构 props 赋值eslint(react/destructuring-assignment ) 我认为这个方法不是正确的方法。

最佳答案

// --- parent.js

import React, { Component, Fragment } from "react";
import { ChildComponent } from './containers/child'

class ParentContainer extends Component {

  handleUpdate = () => {
    // whatever you want to do here
  }

  render(){
    return (
      <Fragment>
        <ChildComponent onUpdate={this.handleUpdate} />
      </Fragment>
    );
  }
}

export default ParentContainer;

// --- child.js

import React, { Component, Fragment } from "react";

export class ChildComponent extends Component {

  this.someAsyncFunction = () => {
    fetch('/just/for/example')
    .then(res => 
        // Do whatever you need here, then hit your function on parent by bubbling the request up the chain
        this.props.onUpdate();
      ) 
  }

  render(){
     return (
      // whatever you want to do with this data
    );
  }
}

关于javascript - 从子进程中的 Promise.then 触发父进程中的 setState 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53861877/

相关文章:

javascript - 使用变量显示错误警报,但如果我直接使用值那么它的工作

reactjs - 如何在 Reactjs 中使用 sequelize 添加或条件

reactjs - 使用接口(interface)属性作为同一接口(interface)中另一个属性的数组长度

javascript - 如何在使用 JavaScript 按住鼠标的同时重复一个函数?

javascript - 无法在 javascript 中为音频设置 currentTime(仅限 IOS)

javascript - react 一个组件正在改变类型复选框的不受控制的输入以被控制

javascript - React 组件中的异步操作

reactjs - React 16.3.*上下文提供者错误: Expected string or class/func but got: Object

Javascript:检查变量是否为假或根本不存在

javascript - 通过比较三个 url 生成 url 列表