React Data Grid - обновление внешних данных - PullRequest
0 голосов
/ 10 мая 2019

Так что я почти наверняка делаю что-то не так, и не понимаю, какая здесь базовая библиотека, но как мне сделать так, чтобы я мог внешне обновить элемент строки до React-Data-Grid?

пример ниже, через 5 с первый столбец первой строки обновляется, но данных в таблице нет.Зачем?и как поменять?

let cols = [
  {
    key: 'sapAssetNumber',
    name: 'SAP Asset number',
    editable: false
  },
  {
    key: 'assetDescription',
    name: 'Description',
    editable: false
  },
  {
    key: 'assetNBV',
    name: 'Asset NBV',
    editable: false
  },
  {
    key: 'salePrice',
    name: 'Sale price',
    editable: false
  }
];

let rows = [
    {
        "id" : "0",
        "sapAssetNumber" : "woof",
        "isAlreadyDisposed" : "",
        "assetDescription" : "test",
        "assetNBV" : "100",
        "salePrice" : "100"
    },
    {
        "id" : "0",
        "sapAssetNumber" : "",
        "isAlreadyDisposed" : "",
        "assetDescription" : "test",
        "assetNBV" : "100",
        "salePrice" : "100"
    },
    {
        "id" : "this",
        "sapAssetNumber" : "is",
        "isAlreadyDisposed" : "a",
        "assetDescription" : "test",
        "assetNBV" : "",
        "salePrice" : ""
    },
    {
        "id" : "jfkhkdafhn",
        "sapAssetNumber" : "",
        "isAlreadyDisposed" : "",
        "assetDescription" : "",
        "assetNBV" : "",
        "salePrice" : ""
    },
    {
        "id" : "kjdsaflkadjsf",
        "sapAssetNumber" : "",
        "isAlreadyDisposed" : "",
        "assetDescription" : "",
        "assetNBV" : "",
        "salePrice" : ""
    },
    {
        "id" : "",
        "sapAssetNumber" : "",
        "isAlreadyDisposed" : "",
        "assetDescription" : "",
        "assetNBV" : "500",
        "salePrice" : "500"
    }
];

class Example extends React.Component {
  constructor() {
  	super();
		
    setTimeout(() => {
    	console.log('changed');
      rows[0].sapAssetNumber = 'meow'
    }, 5000);
  }
  
	render() {
  	return <ReactDataGrid
        columns={cols}
        rowGetter={(i) => rows[i]}
        rowsCount={10}
      />;
  }
}

ReactDOM.render(<Example />, document.querySelector("#app"))
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

.done {
  color: rgba(0, 0, 0, 0.3);
  text-decoration: line-through;
}

input {
  margin-right: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-data-grid/6.1.0/react-data-grid.min.js"></script>

<div id="app"></div>

Ответы [ 2 ]

0 голосов
/ 15 мая 2019

После обсуждения проблем в react-data-grid через GitHub я использовал предоставленное там решение.

, тогда нужно просто позвонить this.refresh().Это не красиво, но, похоже, дыра в RDG

getRowCount() {
    let count = this.props.rows.length;
    if(this.state.refresh && count > 0) {
      count--; // hack for update data-grid
      this.setState({
        refresh: false
      });
    }

    return count;
  }

refresh() {
    this.setState({
      refresh: true
    });
  }
0 голосов
/ 10 мая 2019

переменная row является глобальной переменной в вашем файле. Через 5 секунд переменная строки изменилась, но, поскольку переменная строки не поддерживается ни состоянием компонента примера, ни опорой для компонента примера, изменение не отслеживается методами жизненного цикла компонента примера. Поэтому метод рендеринга компонента Example не вызывается, когда изменяется переменная row, и поэтому ReactDataGrid не получает обновленные значения.

попробуйте сохранить переменную rows в состоянии компонента Example. как это-

let cols = [
    {
      key: 'sapAssetNumber',
      name: 'SAP Asset number',
      editable: false
    },
    {
      key: 'assetDescription',
      name: 'Description',
      editable: false
    },
    {
      key: 'assetNBV',
      name: 'Asset NBV',
      editable: false
    },
    {
      key: 'salePrice',
      name: 'Sale price',
      editable: false
    }
  ];

  let rows = [
      {
          "id" : "0",
          "sapAssetNumber" : "woof",
          "isAlreadyDisposed" : "",
          "assetDescription" : "test",
          "assetNBV" : "100",
          "salePrice" : "100"
      },
      {
          "id" : "0",
          "sapAssetNumber" : "",
          "isAlreadyDisposed" : "",
          "assetDescription" : "test",
          "assetNBV" : "100",
          "salePrice" : "100"
      },
      {
          "id" : "this",
          "sapAssetNumber" : "is",
          "isAlreadyDisposed" : "a",
          "assetDescription" : "test",
          "assetNBV" : "",
          "salePrice" : ""
      },
      {
          "id" : "jfkhkdafhn",
          "sapAssetNumber" : "",
          "isAlreadyDisposed" : "",
          "assetDescription" : "",
          "assetNBV" : "",
          "salePrice" : ""
      },
      {
          "id" : "kjdsaflkadjsf",
          "sapAssetNumber" : "",
          "isAlreadyDisposed" : "",
          "assetDescription" : "",
          "assetNBV" : "",
          "salePrice" : ""
      },
      {
          "id" : "",
          "sapAssetNumber" : "",
          "isAlreadyDisposed" : "",
          "assetDescription" : "",
          "assetNBV" : "500",
          "salePrice" : "500"
      }
  ];

  class Example extends React.Component {
    constructor() {
        super();

        this.state={rows:rows}


    }

    componentDidMount = () =>{
        const context =  this;
        setTimeout(() => {
            rows[0].sapAssetNumber = 'meow'
            context.setState({rows});
      }, 5000);
    }

      render() {
        return <ReactDataGrid
          columns={cols}
          rowGetter={(i) => rows[i]}
          rowsCount={10}
        />;
    }
  }

  ReactDOM.render(<Example />, document.querySelector("#app"));

пожалуйста, прочтите это для ясности состояния компонента: - https://reactjs.org/docs/faq-state.html

Прочтите это, чтобы узнать, когда вызывается метод рендеринга: - https://lucybain.com/blog/2017/react-js-when-to-rerender/

Надеюсь, это решит проблему!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...