javascript - React 组件不刷新或重新渲染

标签 javascript jquery reactjs

setState 正在使用,但 DataTables 在添加或编辑功能后没有刷新。 请关注:

  1. listOfCurrency
  2. 函数ws
  3. 函数onClickSubmitAddCurrency
  4. 组件JSTable
  5. 在 JSTable.js 中标记

货币.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;

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

请指教。

最佳答案

刷新或重新渲染组件的最简单方法是使用键。 你的 key 可以是你在你的状态下的值(value)

state={counter:null}

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

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

React Current Image in Image Gallery

关于javascript - React 组件不刷新或重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51971374/

相关文章:

javascript - 在 CkEditor 中,如何在当前编辑时应用样式表?

javascript - AngularJS,如何更改 CSS 动画规则的值?

jquery - 在其容器底部并排打开聊天 div,Facebook 风格的聊天

css - 尝试在 css 元素中加载背景图像时出现模块解析错误

reactjs - Safari 上出现此警告的原因是什么? "This webpage is using significant energy. Closing it may improve the responsiveness of your Mac"

javascript - Reactjs 将键盘语言自动更改为波斯语

javascript - 如何显示从 Zebra Datepicker 中选择的两个日期中选择的天数?

javascript - 组件获取重复内容而不是刷新

javascript - 通过 jquery 类隐藏元素

javascript - 选择元素上的 jQuery 单击事件在 Chrome 54 上无法按预期工作