簡體   English   中英

從promise.then在子級中觸發父級中的setState函數

[英]Trigger setState function in parent from promise.then in child

我正在嘗試從child promiseparent找到setState的解決方案。

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是想與被觸發thenonSubmit

如果您需要更多詳細信息,請告訴我? 我不希望使用庫或程序包來實現此目的,但是如果它使生活更輕松,我可能會考慮。 Redux可能是最好的選擇,但除非有必要,否則我不希望這樣做。

注意: this.props.handleTransition(); 做這項工作,但esLint返回錯誤Must use destructuring props assignmenteslint(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
    );
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM