如何在React中重新加载表中的数据?

问题描述 投票:0回答:1

我开发了一个从另一个组件(父亲)接收数据的组件。接收数据的组件,第一次正确显示数据,但第二次就不显示了。

第二次调用了metho componentWillReceiveProps,我已经实现了这个功能。但是,尽管如此,数据还是没有刷新。

要想看到这第二次调用的数据,我需要第三次向组件子程序发送数据,在这一刻,我将看到第二次调用的数据。

组件子的代码是。

import React, {Component} from "react";
import { Button, Spinner } from "react-bootstrap";
import BootstrapTable from 'react-bootstrap-table-next';
import { columnsTTShootingFEB, sortedTTShootingFEB } from "../../FEBCOM/column.tables";
import ToolkitProvider from 'react-bootstrap-table2-toolkit';
import "../../../css/content.css";

/**
 * This constat let me have a row with buttons who show or hide columns 
 * 
 * @param {*} param0 
 */
const CustomToggleList = ({
    columns,
    onColumnToggle,
    toggles
  }) => (
    <div className="btn-group btn-group-toggle" data-toggle="buttons" style = {{width: 100 + "%"}}>
      {
        columns
          .map(column => ({
            ...column,
            toggle: toggles[column.dataField]
          }))
          .map((column, index) => {
              if (index > 1){
                return (<button
                type="button"
                key={ column.dataField }
                className={ `btn btn-success btn-sm ${column.toggle ? 'active' : ''}` }
                data-toggle="button"
                aria-pressed={ column.toggle ? 'true' : 'false' }
                onClick={ () => onColumnToggle(column.dataField) }
                >
                    { column.text }
                </button>)
              }
            })
      }
    </div>
  );

class TTShooting extends Component{
    constructor(props){
        super(props);
        this.props = props;
        this.state = {
            loaded: false
        };
    }
componentDidMount(){
    console.log("Componente cargado");
    console.log("id_team_club 1: " + this.props.teams_std_stats[0].id_team_club);
    this.setState({
        loaded: true,
        teams_std_stats: this.props.teams_std_stats
    });
}

componentWillReceiveProps(nextProps){
    this.props = nextProps;
    console.log("id_team_club 2: " + this.props.teams_std_stats[0].id_team_club);
    this.setState({
        teams_std_stats: this.props.teams_std_stats
    });
    console.log("Componente recibe nuevos datos");
}

render(){
    return(
        <div>
            {
                (this.state.loaded) ?
                    <div>
                        {
                            (this.props.language === "es") ?
                                <div>
                                <ToolkitProvider
                                    keyField="id_team_club"
                                    data={ this.state.teams_std_stats }
                                    columns={ columnsTTShootingFEB }
                                    columnToggle
                                    >
                                    {
                                        props => (
                                        <div>
                                            <p className = "text-justify" style = {{fontSize: 12 + "pt"}}><b>Nota: </b>Para añadir o eliminar columnas en la tabla basta hacer clic sobre uno de estos botones</p>
                                            <CustomToggleList { ...props.columnToggleProps } />                                                
                                            <hr />
                                            <BootstrapTable
                                            { ...props.baseProps }
                                            footerClasses = "footer-class"
                                            defaultSorted = { sortedTTShootingFEB }
                                            />
                                        </div>
                                        )
                                    }
                                </ToolkitProvider>
                                </div>
                            :
                                <h2>Pendiente de desarrollo</h2>                                
                        }
                    </div>
                :
                    <div style = {{marginTop: 10 + "px"}}>
                        <Button variant="dark" disabled>
                            <Spinner
                                as="span"
                                animation="border"
                                size="sm"
                                role="status"
                                aria-hidden="true"
                            />
                            <span className="sr-only">
                                {(this.props.language === "es") ? "Cargando datos ..." : "Loading data ..."}
                            </span>
                        </Button>{' '}
                        <Button variant="dark" disabled>
                            <Spinner
                                as="span"
                                animation="grow"
                                size="sm"
                                role="status"
                                aria-hidden="true"
                                />
                                {(this.props.language === "es") ? "Cargando datos ..." : "Loading data ..."}
                        </Button>                    
                    </div>                    
            }
        </div>
    )
}
}

module.exports.TTShooting = TTShooting; 

这段代码在第一次调用和其他次数调用时返回一个日志。第一次返回。

> id_team_club 1: 769

这是正确的。当我发送新的数据是调用了 componentWillReceiveProps 方法,我更新了道具和状态,并显示了 firs 元素的 id_team_club,这是一样的。这个方法被调用了两次。

> id_team_club 2: 769 
> Componente recibe nuevos datos
> id_team_club 2
> Componente recibe nuevos datos

但是,如果我再次发送数据,那么我在第二次调用该函数时显示了第二次发送的数据。

> id_team_club 2: 769
> Componente recibe nuevos datos
> **id_team_club 2: 720**
> Componente recibe nuevos datos

我到底做错了什么?如何更新表的数据?

编辑

我更新了 componentWillReceiveProps 的代码,以及我如何将数据传递给表。

componentWillReceiveProps(nextProps){
    if (this.props.teams_std_stats !== nextProps.teams_std_stats) {
        console.log("Vamos a modificar el state");
        this.setState({
          teams_std_stats: nextProps.teams_std_stats
        });
      }
}

                            <ToolkitProvider
                                keyField="id_team_club"
                                data={ this.state.teams_std_stats }
                                columns={ columnsTTShootingFEB }
                                columnToggle
                                >
                                {
                                    props => (
                                    <div>
                                        <p className = "text-justify" style = {{fontSize: 12 + "pt"}}><b>Nota: </b>Para añadir o eliminar columnas en la tabla basta hacer clic sobre uno de estos botones</p>
                                        <CustomToggleList { ...props.columnToggleProps } />                                                
                                        <hr />
                                        <BootstrapTable
                                        { ...props.baseProps }
                                        footerClasses = "footer-class"
                                        defaultSorted = { sortedTTShootingFEB }
                                        />
                                    </div>
                                    )
                                }
                            </ToolkitProvider>

但是,这并不奏效。

javascript reactjs
1个回答
3
投票

在react中,你不应该改变道具,一个组件的道具是只读的。

 this.props = nextProps;

请阅读这篇关于道具的文章 道具只读


1
投票

不要在生命周期方法中突变道具。渲染函数将始终拥有更新的道具,你不需要设置 this.props.

  componentWillReceiveProps(nextProps) {
    if (this.props.teams_std_stats !== nextProps.teams_std_stats) {
      this.setState({
        teams_std_stats: nextProps.teams_std_stats
      });
    }
  }

同时设置 this.props = props 里面的构造函数是错误的。

constructor(props){
        super(props);
        this.state = {
            loaded: false
        };
    }

1
投票

(代表问题作者发布了解决方法,将答案移到答案空间).

问题是由于数据。因为没有正确到达。这些数据是在事件发生后通过查询数据库得到的,当我分配事件发生的元素的id时,这些数据没有正确地分配给状态。

为了正确地将值分配给状态,我必须这样做。

async handleChange(event){
    /**
     * If you want to access the event properties in an asynchronous way, you should call event.persist() on the event, which will remove
     * the synthetic event from the pool and allow references to the event to be retained by user code.
     */
    event.persist();
let season = this.state.seasons.find((item) => {
    return parseInt(item.id) === parseInt(event.target.value)
});        

this.setState({
    itemSelected: season.id,
});
}

0
投票

正如其他人指出的那样 问题与修改道具有关 但我还想补充一点,我认为没有必要在道具上做文章 team_std_stats 为了使它成为你的组件状态的一部分,你可以直接从你的渲染函数中的道具中引用它,为什么不直接这样做呢?

试试这行

data={ this.props.teams_std_stats }

而不是

 data={ this.state.teams_std_stats }

为您 <ToolkitProvider /> 实施。

希望对大家有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.