从promise.then在孩子

时间:2018-12-20 03:01:49

标签: javascript reactjs

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

parent component

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中的then中触发onSubmit的地方

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

注意:this.props.handleTransition();可以完成工作,但是esLint返回的错误为Must use destructuring props assignmenteslint(react/destructuring-assignment),我认为此方法不是正确的方法。

1 个答案:

答案 0 :(得分:1)

// --- 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
    );
  }
}