gpt4 book ai didi

javascript - 渲染后无法更新表的数据

转载 作者:行者123 更新时间:2023-11-29 23:25:15 26 4
gpt4 key购买 nike

import React from 'react';
import { observer } from "mobx-react"
import { inject } from "mobx-react"
import { deleteTradeData } from "../Actions/Actions"
import axios from "axios"
@observer
export default class TradeTable extends React.Component {


componentDidMount() {

//Adding data of db into mobx store
axios.get(`http://localhost:8091/trade`)
.then(res => {
this.props.store.arr = res.data;
console.log(res.data ,"resssssdata")
})

}

delete = (id) => {
console.log(id + "wdccerfec")
deleteTradeData(id);
window.location.reload();
}

edit = (id) => {
console.log(id + "iddddddddddddddddddddd")

this.props.store.editId = id;
this.props.store.formToggleFlag = false;
// alert("hi")
// window.location.reload();
}
render() {

var tableData = this.props.store.arr;


return <div className="panel panel-default">
{this.props.store.newTradeRender}
<div className="panel-body tradeComponent div-background table-responsive">
<table className="table table-striped tb div-lightbackground">

<thead className="thead-dark ">
<tr>
<th>Date</th>
<th>Commodity</th>
<th>Side</th>
<th>Qty (MT)</th>
<th>Price (MT)</th>
<th>Counterparty</th>
<th>Location</th>
<th></th>
</tr>
</thead>
<tbody>

{
tableData.map((tableItem, index) => {
return (
<tr key={index * Math.random()}>
<td>{tableItem.tradeDate}</td>
<td>{tableItem.commodity}</td>
<td>{tableItem.side}</td>
<td>{tableItem.quantity}</td>
<td>{tableItem.price}</td>
<td>{tableItem.counterparty}</td>
<td>{tableItem.location}</td>

<td>

<button type='submit' className="btn btn-primary table-style" onClick={this.delete.bind(this, tableItem.id)} >
<span className="glyphicon glyphicon-trash" aria-hidden="true"></span>
</button>

</td>
<td>

<button type='submit' className="btn btn-primary table-style edit edit-button" onClick={this.edit.bind(this, tableItem.id)} >
<span className="glyphicon glyphicon-pencil selected-glyph edit-pencil" aria-hidden="true"></span>
</button>
</td>

</tr>)
})
}

</tbody>
</table>
</div>
</div>
}
}

上述代码在其他组件中的 Action 被触发时呈现(这是我的逻辑)。

问题是贸易表组件的呈现不会导致表数据的更新。现在这种行为是预期的,因为组件确实挂载是在呈现之后调用的,因此由于商店数据没有更新所以贸易表没有更新。

但是我无法解决这个问题。我试过组件将挂载并更新,但这会导致一些奇怪的行为(更新表循环运行),导致我的系统和浏览器卡住。所以我不能使用它。是否有任何逻辑或替代方案?

最佳答案

在 React JS 中,您不能通过执行 this.props.store.arr = res.data; 来更改 props。这是因为在 React JS 中存在单向数据流,这意味着数据只能沿一个方向流动,即从父级到子级。因此,更改 props 的唯一方法是更改​​父级传递的值。

此外,ReactJS 仅在特定条件下重新渲染。一种是在 reactJS 状态发生变化时,另一种是使用 shouldComponentUpdate。您必须使用 setState 更改 React 状态。如果你改变像 this.state.foo = "bar" 这样的状态,React 将不会重新渲染。

关于javascript - 渲染后无法更新表的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49548289/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com