React:需要调用父组件重新渲染子组件

11

我创建了一个带有行和子行的表格。当我删除一个子行时,需要重新渲染整个组件。

import React from 'react';
import ReactDOM from 'react-dom';
import auth from './auth'

export class FormList extends React.Component{

  constructor(props) {
    super(props);
    auth.onChange = this.updateAuth.bind(this)
    this.state = {results: []};
  }

  componentWillMount() {
    auth.login();
  }

  // call to get the whole list of forms for react to re-render.
  getForms() {
    if(this.state.loggedIn) {
      $.get(call server url, function(result) {
        this.setState({
             results: result.data.forms
        });
      }.bind(this));
    }
  }

  updateAuth(loggedIn) {
    this.setState({
     loggedIn: loggedIn
    });
    this.getForms()
  }

  componentDidMount() {
    this.getForms()
  }

  render() {
    return (
    <FormTable results={this.state.results} /> 
    )
 }
};

class FormTable extends React.Component{

  render() {
    return ( 
      <table className="forms">
       <thead>
         <tr>
            <th>Form Name</th>
            <th></th>
            <th style={{width: "40px"}}></th>
         </tr>
       </thead>
       {this.props.results.map(function(result) {
            return <FormItem key={result.Id} data={result} />;
        })}         
      </table>
    )
  }
};

class FormItem extends React.Component{
  render() {
    return (
      <tbody>
        <tr className="form_row">
          <td>{this.props.data.Name}</td>
          <td></td>
        </tr>
        {this.props.data.map(function(result) {
            return <FormTransaction key={result.Id} data={result} />;
        })} 
      </tbody>
    )
  }
};

class FormTransaction extends React.Component{

  render() { 
    return (
      <tr className="subform_row">
          <td>{this.props.data.date}</td>
          <td></td>
          <td data-enhance="false">
          <DeleteTransaction data={this.props.data.Id} />
      </tr>
    )
  }
};

class DeleteTransaction extends React.Component {
  constructor(props) {
    super(props);
    this.state = {Id:props.data};
    this.handleDelete = this.handleDelete.bind(this);
   }

   // deletes a sub row and calls get forms to re-render the whole react.
   handleDelete(event) {
     $.ajax({
      url: server url + this.state.Id,
      type: 'DELETE',
      data: {},
      dataType: 'json',
      success: function(result, status) {
          console.log(this);
          // need to call get forms here
      },
      error: function(jqXHR, status, error) {
          console.log(jqXHR);
      }
     });*/
  }

  render() {
    return(
      <i className="danger" onClick = {this.handleDelete}>X</i>
    )
  }
};

ReactDOM.render(
  (<FormList/>),
  document.getElementById('react-forms')
);

所以在handledelete方法成功删除后,我需要调用getforms方法。

我对React和使用ES6都不太熟悉。我尝试将deletetransaction扩展到formslist,并调用super.getForms。但那也没用。任何帮助都将不胜感激。


1
你可以尝试使用级联的属性函数调用...或者你应该尝试使用Flux/Redux模式,以便有一个动作可以为你完成这个操作。 - John Ruddell
我尝试将getForms函数作为组件间的属性进行传递。但是当删除交易实际调用getforms方法时,“this”对象的范围是handletransaction方法。我在handledelete方法中调用“this.state.getForms()”。 - Kumar R
你应该首先绑定getForms,然后可以清理整个组件以使其更简洁。 - John Ruddell
2个回答

12

您也可以通过子组件的 props将来自父组件的函数传递给子组件,并在子组件中执行这个函数。当子组件执行该函数时,您可以简单地调用传入的函数。

例如:

var ParentComponent = React.createClass({
    update: function() {
        this.setState({somethingToUpdate: "newValue"});
        console.log("updated!");
    },
    render: function() {
      <ChildComponent callBack={this.update} />
    }
})

var ChildComponent = React.createClass({
    render: function() {
      <button onClick={this.props.callBack}>click to update parent</button>
    }
})

但这不会导致父组件重新渲染。 - Maysam Torabi
4
你可以在update()函数内部调用this.setState(),以重新渲染ParentComponent。 - Jozef Mikušinec

0
无论何时您尝试在另一个函数中调用 this.setState,它都不会知道您正在设置状态。
例如,在您的代码中,您有 $.get(... function(response){... this.setState()..}
因为 this.setState 在函数(response)内部,所以this将指向函数(response),而不是指向根类。
因此,您需要在 $.get 调用之前将 this 保存在变量中。
var self = this; 并在函数内部使用 self.setState(...) 而不是 this.setState(...)
希望能帮到您。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接