【发布时间】:2019-07-24 17:49:55
【问题描述】:
更新 react 组件方法 componentDidMount 中的 state 属性 data 值,而不是更新 react-table 数据。
在构造函数中调用 getData 可以正常工作。
App.js
class App extends React.Component {
constructor() {
super();
this.state = {
data: []
};
}
getData() {
var MOUNTAINS = [
{name: "Kilimanjaro", height: 5895, country: "Tanzania"},
{name: "Everest", height: 8848, country: "Nepal"},
{name: "Mount Fuji", height: 3776, country: "Japan"},
{name: "Mont Blanc", height: 4808, country: "Italy/France"},
{name: "Vaalserberg", height: 323, country: "Netherlands"},
{name: "Denali", height: 6168, country: "United States"},
{name: "Popocatepetl", height: 5465, country: "Mexico"}
];
return MOUNTAINS;
}
componentDidMount() {
this.setState({ data : this.getData()}, () => {
console.table(this.state.data);
});
}
render() {
const { data } = this.state;
return <T data={data} />;
}
}
T.js
export default class T extends Component {
constructor(props) {
super(props);
debugger;
this.state = {
data: props.data
};
}
render() {
return (
<div>
<ReactTable
data={this.state.data}
columns={[{
Header: "Name",
accessor: "name"
},{
Header: "Height",
accessor: "height"
},{
Header: "Country",
accessor: "country"
}]}
defaultPageSize={10}
className="-striped -highlight"
/>
<br />
</div>
);
}
}
【问题讨论】:
-
它会在您的控制台中打印数据吗?
-
是的,它打印数据。
-
正如@dacre 所指出的,原因是正确的。您还可以在
T组件中使用getDerivedStateFromProps并根据将触发重新渲染的道具更新状态。
标签: reactjs react-table