React组件不会刷新或重新渲染

时间:2018-08-22 16:31:41

标签: javascript jquery reactjs

setState正在使用中,但添加或编辑功能后DataTables不会刷新。 请重点关注:

  1. listOfCurrency
  2. 功能 ws
  3. 函数 onClickSubmitAddCurrency
  4. 组件 JSTable
  5. JSTable.js中的
  6. 标记

Currency.js

   componentWillMount() {
    this.setState(
        {
            listOfCurrency: [],
            currency: { currency: '', symbol: '', status: '' },
            myCurrencyRate: { exchangeRate: 0, adminFee: 0 },
            currencyRateRequest:{exchangeRate:'',processFee:'',earnrate:'',earnAdminFee:''},
            myCurrency: { currency:''},
            isAdmin:false,
            message: '',
            snackbar: {
                open: false,
                vertical: null,
                horizontal: null,
            },

        }
    );

    var checkAccessRightUrl=properties.domain+properties.checkAccessRightUrl;
    this.wsCheckUrlAccess(checkAccessRightUrl,'Currency');

    var wsListUrl = properties.domain + properties.currencyList;
    this.ws(wsListUrl, false, false, 'get', null, false,'list');

    var populateMyMembershipCurrencyRate = properties.domain + properties.populateMembeshipCurrencyRate;
    this.wsbind(populateMyMembershipCurrencyRate,'currencyRate');

    var myMembershipCurrency = properties.domain + properties.showMyMembershipCurrency;
    this.wsbind(myMembershipCurrency,'myMembershipCurrency');

    var checkIsAdminUrl = properties.domain + properties.populateCheckIsAdmin;
    this.wsbind(checkIsAdminUrl,'checkIsAdmin');
}

ws(wsurl, jsonLibrary, toggle, process, senditem, snackbar,processName) {
    var accessToken = sessionStorage.getItem('accessToken');
    var reqs;
    if (process === 'post') {
        reqs = Request.post(wsurl)//wsurl
    } else if (process === 'get') {
        reqs = Request.get(wsurl)//wsurl
    }
    reqs.set('Authorization', 'Bearer ' + accessToken)
        .set('Content-Type', 'application/json')
    if (senditem != null) {
        reqs.send(senditem)
    }
    reqs.end((err, res) => {
        if (res.status === 200) {
            if(processName === 'currencyRate'){
                this.setState(
                    {
                        isLoading:false,
                        currencyRateRequest: res.body,
                        message: (res.body===null?'':res.body.message),
                        snackbar: {
                            vertical: 'top',
                            horizontal: 'right',
                            open: snackbar
                        },
                    }
                );
            }else{
                this.setState(
                    {
                        isLoading:false,
                        listOfCurrency: (jsonLibrary ? JSON.parse(JSON.stringify(res.body.responses)) : res.body),

                        message: (res.body===null?'':res.body.message),
                        snackbar: {
                            vertical: 'top',
                            horizontal: 'right',
                            open: snackbar
                        },
                    }
                );
            }

            if (toggle) {
                this.togglePrimary();
            }

        } else {
            this.checkSession(res);
            console.log('do logout function here');
            console.log(err);
        }
    });
}

onClickSubmitAddCurrency() {
    var wsListUrl = properties.domain + properties.addCurrency;
    this.ws(wsListUrl, true, true, 'post', this.state.currency, true);
};
   render() {
    return (
        <div className="animated fadeIn">

            <CardBody>
                <JSTable id='#currencyTable' 
                        dataSet={this.state.listOfCurrency} columns={columns} 
                        onEdit={this.onClickGotoEdit.bind(this)} onDelete={this.onClickSubmitDeleteCurrency.bind(this)} />
            </CardBody>

        </div>
    );
}

JSTable.js

import React, { Component } from 'react';
import { Card, CardBody, CardHeader, Col, Row,Button } from 'reactstrap';
import '../../css/jquery.dataTables.css';
import '../../css/dataTables.responsive.css';

const $ = require('jquery');
var ReactDOM = require('react-dom');
$.Datatable = require('datatables.net-responsive');

class JSTable extends Component {

constructor(props) {
    super(props);
    this.state = {
        //ajaxurl    : props.ajaxurl,
        id      : props.id,
        dataSet : props.dataSet,
        columns : props.columns,
        onEdit  : props.onEdit,
        onDelete: props.onDelete,
        onTopUp : props.onTopUp,
        render  : {
            edit    :props.onEdit==null?{display:'none'}:{display:''},
            delete  :props.onDelete==null?{display:'none'}:{display:''},
            topup   :props.onTopUp==null?{display:'none'}:{display:''},
        },
        indicator:{
            edit    :props.onEdit==null?true:false,
            delete  :props.onDelete==null?true:false,
            topup   :props.onTopUp==null?true:false,
        }
    };
}


componentDidMount() {

    this.$el = $(this.el);
    this.$el.DataTable({
       // ajax: this.state.ajaxurl,
        data: this.state.dataSet,
        columns: this.state.columns,
        responsive: true,
        columnDefs: [{
            targets: 0,
            createdCell: (td, cellData, rowData, row, col) =>
                ReactDOM.render(
                    <div>
                        <Button color="primary" style={this.state.render.edit} 
                            onClick={this.state.indicator.edit?this.empty:this.state.onEdit.bind(this.celldata,this,rowData,this.row,this.col)}
                             className="mr-1">Edit</Button>

                        <Button color="primary" style={this.state.render.delete}
                            onClick={this.state.indicator.delete?this.empty:this.state.onDelete.bind(this.celldata,this,rowData,this.row,this.col)}
                             className="mr-1">Delete</Button>

                        <Button color="primary" style={this.state.render.topup}
                            onClick={this.state.indicator.topup?this.empty:this.state.onTopUp.bind(this.celldata,this,rowData,this.row,this.col)} 
                            className="mr-1">Top Up</Button>
                    </div>, td
                ),

            }
        ],

    });

}

// componentWillUnmount() {
//     this.$el.DataTable.destroy(true);
// }

empty(){
    console.log('===========no function=================');
}
render() {
    return (
        <div className="animated fadeIn">
            <table data={this.state.dataSet} className="display" width="100%" ref={el => this.el = el}>

            </table>
        </div>
    );
}

}

export default JSTable;

我可以获取更新数据。但是,它不会更新表。除非我刷新页面。

请告知。

2 个答案:

答案 0 :(得分:3)

刷新或重新呈现组件的最简单方法是密钥。 您的钥匙可以是您所在州的价值

state={counter:null}

然后从API加载数据时 使用setState并增加计数器

<table key={this.state.counter}>
   //your code
</table>

React Current Image in Image Gallery

答案 1 :(得分:0)

您可以使用this.forceUpdate()在reactJs中重新渲染。